Last active
February 21, 2023 04:07
-
-
Save nikolaydubina/590133887f84c8961c2fab45b91af05c to your computer and use it in GitHub Desktop.
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
// https://go.dev/play/p/_Gt8U6GFkPk | |
// go embedding field mechanics ⚙️ | |
package main | |
import ( | |
"fmt" | |
"unsafe" | |
) | |
type A struct { | |
X int | |
Y int | |
} | |
func (s A) Validate() { | |
fmt.Println("a", s.X, s.Y) | |
} | |
func (s A) GetX() int { return s.X } | |
type B struct { | |
X int | |
A | |
} | |
func (s B) Validate() { | |
fmt.Println("b", s.X, s.Y, "b.a", s.A.X, s.A.Y) | |
} | |
func main() { | |
// on field assignment only outer struct field is updated | |
b := B{X: 1, A: A{X: 2, Y: 3}} | |
fmt.Printf("%#v\n", b) | |
b.X = 5 | |
b.Y = 10 | |
fmt.Printf("%#v\n", b) | |
// method that is not overwritten, will read overwritten field from inner struct | |
fmt.Println("b.a.GetX()", b.A.GetX()) | |
// only outer struct method is called | |
// it accesses outer struct field | |
b.Validate() | |
// only extra fields are physically stored in outer struct | |
a := A{X: 2, Y: 3} | |
fmt.Println("size b", unsafe.Sizeof(b), "size b.a", unsafe.Sizeof(b.A), "size of a", unsafe.Sizeof(a)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment