在Go中,如果您定义一个新类型,例如:
type MyInt int
Run Code Online (Sandbox Code Playgroud)
然后,您无法将a传递MyInt给期望int的函数,反之亦然:
func test(i MyInt) {
//do something with i
}
func main() {
anInt := 0
test(anInt) //doesn't work, int is not of type MyInt
}
Run Code Online (Sandbox Code Playgroud)
精细.但是为什么同样不适用于功能呢?例如:
type MyFunc func(i int)
func (m MyFunc) Run(i int) {
m(i)
}
func run(f MyFunc, i int) {
f.Run(i)
}
func main() {
var newfunc func(int) //explicit declaration
newfunc = func(i int) {
fmt.Println(i)
}
run(newfunc, 10) //works just fine, even though types seem to differ
} …Run Code Online (Sandbox Code Playgroud) 我有以下代码:
type FWriter struct {
WriteF func(p []byte) (n int,err error)
}
func (self *FWriter) Write(p []byte) (n int, err error) {
return self.WriteF(p)
}
func MyWriteFunction(p []byte) (n int, err error) {
// this function implements the Writer interface but is not named "Write"
fmt.Print("%v",p)
return len(p),nil
}
MyFWriter := new(FWriter)
MyFWriter.WriteF = MyWriteFunction
// I want to use MyWriteFunction with io.Copy
io.Copy(MyFWriter,os.Stdin)
Run Code Online (Sandbox Code Playgroud)
我想要做的是创建一个Writer接口来包装MyWriteFunction,因为它没有命名为"Write",我不能将它用于任何需要"Writer"接口的东西.
这段代码不会起作用,因为它抱怨:
method MyWriterFunction is not an expression, must be called
Run Code Online (Sandbox Code Playgroud)
我在这做错了什么?如何将WriteF设置为MyWriteFunction?
注意:我尽可能地简化了这个问题,实际上我有一个具有MyWriteFunction和一个普通Write函数的结构,所以它有点复杂......(如果有更好的方法来解决我的这个问题)那么我很高兴听到它!)
谢谢!!
编辑::我注意到我的拼写错误并修复了它(MyWriterFunction - …