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"))
    }
}
3
  • 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: stackoverflow.com/a/44372954/2536252 Commented Mar 18, 2020 at 4:07
  • 1
    See Why is my nil error value not equal to nil? for an explanation. Commented Mar 18, 2020 at 4: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? Commented Aug 20, 2021 at 10:41

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.