普通网友 2018-02-17 20:42
浏览 19
已采纳

转:输入的指针与接口不兼容

I'm not sure how to formulate the question properly. I have 2 go code snippets that should do the exact same thing but apparently they don't, since one works and the other doesn't (doesn't compile)

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)

}

Playground

main() works and main2() doesn't.

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

The only difference is that I used an intermediate variable but I'm not doing any pointer referencing or dereferencing.

What am I doing wrong here?

  • 写回答

1条回答 默认 最新

  • dongtiran7769 2018-02-18 11:59
    关注

    You shouldn't use pointers to interfaces, it is a bad practice in Go.
    And about code that doesn't compile - when you create an intermediate variable logWriter you allocate an interface variable, that has its own allocated memory to describe what it stores (actual type) and a reference to the actual structure.
    That is why &logWriter and &file have different types.
    But as I sad previously, you should not use pointers to interfaces, just use interface type and do not get address of interface type variable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable