Skip to content

Instantly share code, notes, and snippets.

@AlbinoDrought
Created Feb 17, 2022
Embed
What would you like to do?
Why is nil != nil in Go sometimes
package main
import "log"
// some random interface
type User interface {
Name() string
}
// some implementation of that interface
type inMemoryUser struct {
name string
}
func (user *inMemoryUser) Name() string {
return user.name
}
// something that returns our implementation
func findInMemoryUser(id string) *inMemoryUser {
// (always returns nil for this demo)
if id == "cool-dude" {
return &inMemoryUser{name: "Cool Dude"}
}
return nil
}
// something that returns our implementation as the interface
func FindUserByID(id string) User {
return findInMemoryUser(id)
}
func main() {
user := FindUserByID("random-man")
if user != nil {
log.Printf("not nil %+v, let me say hello:", user)
log.Printf("hello %v", user.Name())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment