iTranslated by AI
When nil is not nil (or Go programmers inject dependencies as they breathe)
This is another small tip. It's a familiar topic for those who write code in Go, but I happened to come across it.
The subject is this code:
package main
import "fmt"
func main() {
var a *string = nil
var b interface{} = a
fmt.Println("a == nil:", a == nil) // true
fmt.Println("b == nil:", b == nil) // false
fmt.Println("a == b: ", a == b) // true
}
You can see the actual execution result here.
In Go, nil represents a state with a pointer value, referring to what is commonly called a "null reference." If it were just that, b == nil would likely be true, but it becomes a bit more complex when an interface type is involved.
In fact, an interface type is conceptually a struct that has references to the type and the value as its elements. It looks like this when illustrated (quoted from "Go Data Structures: Interfaces").
For a struct to be considered a zero value, all elements of the struct must be zero values. In this context, for an instance of an interface type to be nil, both the type and the value (reference) must be nil.
With this in mind, let's look at the previous code again:
var a *string = nil
var b interface{} = a
Variable a is a "*string type with a nil value." By assigning this to b, which is an interface{} type, b has an internal state of "type is *string, value is nil." This means b == nil is not true. On the other hand, a == b is a "comparison of values," and since both are comparable and both are the same nil, it results in true.
In Go, "structural subtyping" is achieved through this function and nature of the interface type.
It is often explained that Go's interface type is "something like a template or interface in C++ or Java," but abstract types in C++ or Java are basically "nominal subtyping," and the underlying design philosophy is different. By the way, Rust's traits are also nominal.
What is great about structural subtyping is that "dependency injection" becomes incredibly easy.
Looking back at:
var a *string = nil
var b interface{} = a
It might be easier to understand if you think of it as "injecting a into b." In other words, "b == nil" can be seen as an expression to check, "Has anything been injected into b?" The important point here is that there is no relationship explicitly stated in the code beforehand between the types of a and b. The wonderful and scary thing about Go is that even if there is no explicit relationship, if the structures "happen to be the same," you can inject them (lol).
Well, it cannot be denied that the introduction of generics was delayed because dependency injection via structural subtyping is just too convenient (just a guess).
💡 Go programmers inject dependencies as naturally as they breathe. 💡

Discussion