Go: Pointer to type is incompatible with interface
我不确定如何正确地提出问题。 我有2个go代码段,它们应该做完全相同的事情,但显然它们不行,因为一个有效,而另一个无效(不编译)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | func writeSomething(writer *io.Writer) { } func main() { file, _ := os.Create("error.log") var logWriter io.Writer = file writeSomething(&logWriter) } func main2() { file, _ := os.Create("error.log") writeSomething(&file) } |
操场
main()有效,而main2()无效。
prog.go:20:17: cannot use &file (type **os.File) as type *io.Writer in argument to writeSomething:
*io.Writer is pointer to interface, not interface
唯一的区别是,我使用了中间变量,但没有进行任何指针引用或取消引用。
我在这里做错了什么?
您不应该使用指向接口的指针,这在Go中是一种不好的做法。
关于无法编译的代码-创建中间变量
这就是
但是,正如我之前难过的那样,您不应使用指向接口的指针,而应仅使用接口类型并且不获取接口类型变量的地址。