Skip to content

Instantly share code, notes, and snippets.

@mtilson
Last active March 10, 2020 13:50
Show Gist options
  • Save mtilson/c21e603ab63d6322fec4b3b592129bbb to your computer and use it in GitHub Desktop.
Save mtilson/c21e603ab63d6322fec4b3b592129bbb to your computer and use it in GitHub Desktop.
why you have to avoid the assignment of the dysfunctional value to the interface [golang]
// https://play.golang.org/p/1hGHFwjlwud
package main
import (
"bytes"
"fmt"
"io"
)
func main() {
var w1 *bytes.Buffer
var w2 io.Writer
fmt.Printf("w1: %T\n", w1) // *bytes.Buffer
fmt.Printf("w2: %T\n", w2) // <nil>
if w2 != nil {
fmt.Println(" ... doing something with w2 - it panics here")
}
var w3 *bytes.Buffer = nil
var w4 io.Writer = nil
fmt.Printf("w3: %T\n", w3) // *bytes.Buffer
fmt.Printf("w4: %T\n", w4) // <nil>
if w4 != nil {
fmt.Println(" ... doing something with w4 - it panics here")
}
var w5 *bytes.Buffer
var w6 io.Writer = w5
fmt.Printf("w5: %T\n", w5) // *bytes.Buffer
fmt.Printf("w6: %T\n", w6) // *bytes.Buffer
if w6 != nil {
fmt.Println(" ... doing something with w6 - it panics here")
}
}
w1: *bytes.Buffer
w2: <nil>
w3: *bytes.Buffer
w4: <nil>
w5: *bytes.Buffer
w6: *bytes.Buffer
... doing something with w6 - it panics here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment