2025-04-10 17:45:32 +08:00

54 lines
1.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import "fmt"
// 定义一个Person结构体
type Person struct {
Name string
Age int
}
// 给Person结构体定义一个方法
func (p Person) Greet() {
fmt.Printf("Hello, my name is %s and I'm %d years old.\n", p.Name, p.Age)
}
// 嵌套结构体示例
type Employee struct {
Person
JobTitle string
}
func main() {
// 结构体初始化方式1字段顺序
p1 := Person{"Alice", 25}
// 结构体初始化方式2字段名指定
p2 := Person{
Name: "Bob",
Age: 30,
}
// 访问结构体字段
fmt.Println(p1.Name) // Alice
fmt.Println(p2.Age) // 30
// 调用结构体方法
p1.Greet() // Hello, my name is Alice and I'm 25 years old.
p2.Greet() // Hello, my name is Bob and I'm 30 years old.
// 嵌套结构体初始化
emp := Employee{
Person: Person{
Name: "Charlie",
Age: 35,
},
JobTitle: "Developer",
}
// 访问嵌套结构体字段
fmt.Println(emp.Name) // Charlie (提升字段)
fmt.Println(emp.JobTitle) // Developer
emp.Greet() // Hello, my name is Charlie and I'm 35 years old.
}