Created
November 1, 2020 12:45
-
-
Save gerrywastaken/f18cc4ad6377fa910763bd673913634e to your computer and use it in GitHub Desktop.
Gotchas in Go-lang
This file contains hidden or 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
// 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