Recently, I am reading "The Go Progrmming Language" Book. In the chapter 7.5, I am confused about below code. Why f(buf) will panic but f(w)?
package main
import (
"bytes"
"fmt"
"io"
"os"
)
func main() {
var w io.Writer
fmt.Printf("%T\n", w)
f(w)
w = os.Stdout
fmt.Printf("%T\n", w)
w = new(bytes.Buffer)
fmt.Printf("%T\n", w)
var buf *bytes.Buffer
fmt.Printf("%T\n", buf)
f(buf)
}
func f(out io.Writer) {
fmt.Printf("%T\n", out)
if out != nil {
out.Write([]byte("done!\n"))
}
}
bufpass as a pointer*bytes.Buffertof(). Pointers are special types that contain the memory address of the underlying value. An interface at runtime holds an object that implements its interface. You can also check this link: stackoverflow.com/a/44372954/2536252