1 回答

TA貢獻2080條經(jīng)驗 獲得超4個贊
將以下函數(shù)添加到包中,以確保在編譯時輸入和輸出類型匹配:
func assertArgAndResult() {
var v MyInterface
v.Method2(v.Method1())
}
只要不調(diào)用該函數(shù),該函數(shù)就不會包含在可執(zhí)行文件中。
沒有編譯時檢查可以確保它MyType是問題中指定的結(jié)構(gòu)類型。
reflect 包可用于完全檢查類型類型。
// checkItf returns true of the interface value pointed to by
// pi has Method1 with some return type T and Method2 with
// argument type T.
func checkItf(pi interface{}) bool {
t := reflect.TypeOf(pi)
if t.Kind() != reflect.Ptr {
return false // or handle as error
}
t = t.Elem()
if t.Kind() != reflect.Interface {
return false // or handle as error
}
m1, ok := t.MethodByName("Method1")
// Method1 should have no outputs and one input.
if !ok || m1.Type.NumIn() != 0 || m1.Type.NumOut() != 1 {
return false
}
// Method2 should have one input and one output.
m2, ok := t.MethodByName("Method2")
if !ok || m2.Type.NumIn() != 1 || m2.Type.NumOut() != 1 {
return false
}
e := reflect.TypeOf((*error)(nil)).Elem()
s := m1.Type.Out(0)
// The type must be a struct and
// the input type of Method2 must be the same as the output of Method1 and
// Method2 must return error.
return s.Kind() == reflect.Struct &&
m2.Type.In(0) == s &&
m2.Type.Out(0) == e
}
像這樣稱呼它:
func init() {
if !checkItf((*MyInterface)(nil)) {
panic("mismatched argument and return time son MyInterface")
}
}
- 1 回答
- 0 關(guān)注
- 140 瀏覽
添加回答
舉報