7 ms·
Go's nil is statically-typed. The nil keyword is polymorphic (as numbers in the source code are) but individual nils that occur at runtime in Go are actually ty
by jerf 10y ago
Go's nil is statically-typed. The nil keyword is polymorphic (as numbers in the source code are) but individual nils that occur at runtime in Go are actually typed. You can actually put methods on them and they execute just fine:
type S struct{}
func (s *S) Test() {
if s == nil {
fmt.Println("Nil pointer")
} else {
fmt.Println("Not nil pointer")
}
}
func main () {
var p *S
p.Test()
}
That will print "Nil pointer", not crash.
While I'm actually still in agreement that I don't love a language with nil pointers, it is less bad in Go because they are less pointy and stabby. It's not like C where they are automatically a crashing offense; they are valid values treated in sensible ways in a lot more places than in C, because in Go they still have their type associated with them. But I'd still like to be able to declare a non-nillable pointer type.
Please do note carefully the difference between less bad and not bad.
- Zak 10y agoThe type of s/p there can't be guaranteed to be (S not nil) at compile time, which is a bizarre decision in an otherwise-statically-typed language where the type system is designed to provide runtime type safety. You still have to do a null check at runtime if you want to be safe here While it's nicer that you can perform the check inside Test() instead of before the call, I don't understand why the type system doesn't just prohibit this and make you use a union type if you want (S or nil) given that a lot more situations call for (S not nil) than (S or nil).