Embedded Structs Promote Fields And Methods

Embed a struct anonymously so its fields and methods are promoted onto the outer type, including through deeper nesting levels.

GoConfig Management

Code

gosnippet
33 lines
package main

import "fmt"

type Base struct {
	ID   string
	Name string
}

func (b Base) Describe() string { return b.Name + " (#" + b.ID + ")" }

// 匿名嵌入(embedded):字段与方法被提升(promoted)到外层类型
type Admin struct {
	Base
	Level int
}

// 深层嵌入:提升逐级穿透
type Deep struct {
	Admin
}

func main() {
	a := Admin{Base: Base{"u1", "ada"}, Level: 9}
	// 提升字段:像直接字段一样访问,无需 a.Base.Name
	fmt.Println(a.Name, a.ID, a.Level)
	// 提升方法:同样直达
	fmt.Println(a.Describe())

	d := Deep{Admin: a}
	fmt.Println(d.Name, d.Level) // 两层嵌入依然可直达
	fmt.Println(d.Describe())
}

Inside the snippet

Embedded Structs Promote Fields And Methods keeps everything in the functions Describe and main.

Putting it to use

The primary signature is func (b Base) Describe() string

Treat main as the orchestrator calling Describe in a fixed order.

Core lines

func (b Base) Describe() string { return b.Name + " (#" + b.ID + ")" }
func main() {
	a := Admin{Base: Base{"u1", "ada"}, Level: 9}
	// 提升字段:像直接字段一样访问,无需 a.Base.Name
	fmt.Println(a.Name, a.ID, a.Level)
	// 提升方法:同样直达
	fmt.Println(a.Describe())
	d := Deep{Admin: a}
	fmt.Println(d.Name, d.Level) // 两层嵌入依然可直达
	fmt.Println(d.Describe())
}

Interactive Tools for This Topic

FAQ

How do you run Embedded Structs Promote Fields And Methods?
Direct execution is enough; the script has no external requirements.