I'm trying to wrap my head around embedding in golang, and I am a bit confused when it comes to the state of a type embedded in another.
Here is my question: If I have a type Embedii
that is an int, and it has a method that effects its value, should that appear in a type that embeds it?
Here is what I was playing with:
package main
import (
"fmt"
)
type Embedii int
func (y *Embedii) Do() {
if y == nil {
y = new(Embedii)
} else {
*y = *y + 1
}
fmt.Println(*y)
}
type Embedder struct {
*Embedii
}
func main() {
embedii := new(Embedii)
embedii.Do() // prints 1
embedii.Do() // prints 2
fmt.Println("---")
embedder := new(Embedder)
embedder.Do() // prints 0
embedder.Do() // prints 0
fmt.Println("---")
nembedii := new(Embedii)
embedo := &Embedder{nembedii}
embedo.Do() // prints 1
embedo.Do() // prints 2
}
https://play.golang.org/p/ArqKESVWoS-
I'm curious to understand why I have to explicitly pass an existing instance of Embedii
to the Embedder
type for this to work properly