Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@gerrywastaken
Created November 1, 2020 12:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerrywastaken/f18cc4ad6377fa910763bd673913634e to your computer and use it in GitHub Desktop.
Save gerrywastaken/f18cc4ad6377fa910763bd673913634e to your computer and use it in GitHub Desktop.
Gotchas in Go-lang
// Interfaces assigned a value of `nil` are not equal to `nil`
package main
import "fmt"
type I interface {
}
type T struct {
S string
}
func main() {
var i I
var t *T
describe(i)
// Output
// i -> value: <nil>, type: <nil>, equal_nil?: true
// the interface `i` is nil as it hasn't been assigned
i = t
describe(i)
// Output
// i -> value: <nil>, type: *main.T, equal_nil?: false
// the intervace `i` still returns a value of nil, but it's not equal to nil!
// Internally you should think of the value of `i` as a special object like this:
// `i = (value: nil, concrete_type: *T)`
// When you try to Printf('%v', i) it's actually printing `i.value`
// At least this is how I'm currently thinking about it.
}
func describe(i I) {
fmt.Printf(
`
i -> value: %v, type: %T, equal_nil?: %v
`,
i, i, i == nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment