Created
January 30, 2019 16:29
-
-
Save sayotte/450e5105f5004487646f84b3dc48e910 to your computer and use it in GitHub Desktop.
Nil-assignment gotcha
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type Fooer interface { | |
Foo() | |
} | |
type X struct{} | |
func (x X) Foo() { return } | |
func getNilX() *X { | |
return nil | |
} | |
func main() { | |
var fooer Fooer | |
fooer = getNilX() | |
if fooer == nil { | |
fmt.Println("fooer DOES == nil") | |
} else { | |
fmt.Printf("fooer != nil: %v\n", fooer) | |
// we hit this because an interface variable stores both a type and a value | |
// fooer, right now, has been assigned something like: | |
// struct { | |
// typ: reflect.Type | |
// val: reflect.Value | |
// } { | |
// type: reflect.TypeOf(&X{}), | |
// val: *X(nil), | |
// } | |
// So while the VALUE is nil, the variable 'fooer' itself is non-nil. | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fooer != nil: <nil> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment