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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- How do you run Embedded Structs Promote Fields And Methods?
- Direct execution is enough; the script has no external requirements.
Report a problem with this exampleOpens a pre-filled issue on GitHub.