Files
bulma/composite_struct.go

72 lines
1.6 KiB
Go
Raw Permalink 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 (
"encoding/json"
"fmt"
)
// 嵌套结构体(地址信息)
type Address struct {
City string
Street string
}
// 主结构体(用户信息)
type User struct {
ID int
Name string
Age int
Address // 嵌套结构体(匿名字段,可直接访问其字段)
}
// 带标签的结构体
type Person struct {
Name string `json:"name"`
Age int `json:"age,omitempty"`
}
// 结构体方法
func (u *User) GetInfo() string {
return fmt.Sprintf("User: %s, Age: %d, City: %s", u.Name, u.Age, u.City)
}
func main() {
// 初始化带嵌套的结构体
u := User{
ID: 1,
Name: "Alice",
Age: 20,
Address: Address{
City: "Beijing",
Street: "Main St",
},
}
// 访问字段(嵌套字段可直接访问)
fmt.Printf("用户:%+v\n", u)
fmt.Println("城市:", u.City) // 等价于u.Address.City
fmt.Println("用户信息:", u.GetInfo())
// 结构体是值类型:赋值时复制所有字段(包括嵌套字段)
u2 := u
u2.Age = 21
u2.Street = "New St"
fmt.Println("u年龄:", u.Age, "u2年龄:", u2.Age) // 20 21
fmt.Println("u街道:", u.Street, "u2街道:", u2.Street) // Main St New St
// 结构体比较
p1 := Person{Name: "Alice", Age: 25}
p2 := Person{Name: "Alice", Age: 25}
if p1 == p2 {
fmt.Println("p1与p2相等")
}
// 结构体标签:JSON序列化
jsonP, _ := json.Marshal(p1)
fmt.Printf("Person JSON: %s\n", jsonP) // 输出{"name":"Alice","age":25}
p3 := Person{Name: "Bob"} // Age为零值0
jsonP3, _ := json.Marshal(p3)
fmt.Printf("p3 JSON: %s\n", jsonP3) // 输出{"name":"Bob"}Age为0被omitempty忽略)
}