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)
}
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?
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.