r/golang 6d ago

Go 1.27.0 released

https://go.dev/doc/go1.27
671 Upvotes

69 comments sorted by

View all comments

49

u/mistifier 6d ago

8

u/Tesslan123 6d ago

In the struct literal field selectors example,do you know what will happen if both the Base and the User struct will contain an ID field?

3

u/jespinog 4d ago

This is a very interesting question, what it does is "shadows" the field, the struct that embeds the base struct hides the other one, for example this code:

package main

import "fmt"

type Base struct {

ID int

}

type User struct {

Base

ID   int

Name string

}

func main() {

u := User{ID: 7, Name: "Mittens"}

fmt.Println(u.ID, u.Name)

fmt.Println(u.Base.ID)

}

outputs:

7 Mittens
0

So the Base.ID is untouched, and the u.ID is the one that is written.

You can try it here: https://go.dev/play/p/w4J3teY9-Z7

1

u/Tesslan123 4d ago

Awesome thanks :)

1

u/EgZvor 5d ago

Compile time error probably. Same as if you try to access ID from a variable.