Skip to content

Instantly share code, notes, and snippets.

@AlbinoDrought
Created February 17, 2022 06:49
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 AlbinoDrought/f443090b882d2dc1da7bc277f8affc31 to your computer and use it in GitHub Desktop.
Save AlbinoDrought/f443090b882d2dc1da7bc277f8affc31 to your computer and use it in GitHub Desktop.
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