我正在嘗試使功能成為我的結(jié)構(gòu)中的成員type myStruct struct { myFun func(interface{}) interface{}}func testFunc1(b bool) bool { //some functionality here //returns a boolean at the end}func testFunc2(s string) int { //some functionality like measuring the string length // returns an integer indicating the length}func main() { fr := myStruct{testFunc1} gr := myStruct{testFunc2}}我收到錯(cuò)誤:Cannot use testFunc (type func(b bool) bool) as type func(interface{}) interface{}Inspection info: Reports composite literals with incompatible types and values.我無法弄清楚為什么會(huì)收到此錯(cuò)誤。
1 回答

慕田峪4524236
TA貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超5個(gè)贊
您的代碼的問題是結(jié)構(gòu)中的聲明和testFunc. interface{}接受并返回的函數(shù)與interface{}接受并返回的函數(shù)的類型不同bool,因此初始化失敗。您粘貼的編譯器錯(cuò)誤消息就在此處。
這將起作用:
package main
type myStruct struct {
myFun func(bool) bool
}
func testFunc(b bool) bool {
//some functionality here
//returns a boolean at the end
return true
}
func main() {
fr := myStruct{testFunc}
}
- 1 回答
- 0 關(guān)注
- 126 瀏覽
添加回答
舉報(bào)
0/150
提交
取消