0

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"))
    }
}
kose livs
  • 339
  • 3
  • 5
  • `buf` pass as a pointer `*bytes.Buffer` to `f()`. **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: https://stackoverflow.com/a/44372954/2536252 – Adriel Artiza Mar 18 '20 at 04:07
  • 1
    See [Why is my nil error value not equal to nil?](https://golang.org/doc/faq#nil_error) for an explanation. – Charlie Tumahai Mar 18 '20 at 04:46
  • I think all of you answer haven't hit the point. How can you expect a golang newbie know the internal implementation of Go? – kose livs Aug 20 '21 at 10:41

1 Answers1

2

An interface type, in Go, is a pair containing the underlying type and the value. When you create an interface variable:

var w io.Writer

it is initialized to its zero value, which, for interfaces, is nil. When you pass this to a function that expects an io.Writer, it is passed as nil.

The initialization is similar for a non-interface pointer variable:

var buf *bytes.Buffer

Here, buf is nil. However, when you pass buf to a function that takes io.Writer, it has to be passed in as an interface. Go converts the buf value to an interface where the type is *bytes.Buffer and underlying value is nil. However, this interface itself is not nil.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • Maybe you can paste the Type struct and give out how a variable in go represented in inner go implementation. That will be much clear. – kose livs Aug 20 '21 at 10:43