Created
February 17, 2022 06:49
-
-
Save AlbinoDrought/f443090b882d2dc1da7bc277f8affc31 to your computer and use it in GitHub Desktop.
Why is nil != nil in Go sometimes
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 "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