Go Struct Initialization Explained

In Go language, structs can be initialized using literal syntax. For example:

type Person struct {
    Name string
    Age  int
}

func main() {
    // 使用字面量方式初始化结构体
    p := Person{
        Name: "Alice",
        Age:  30,
    }
    
    fmt.Println(p) // 输出: {Alice 30}
}

Instead of initializing a struct using literal syntax, you can also create a struct instance and return its pointer using the “new” keyword, for example:

p := new(Person)
p.Name = "Bob"
p.Age = 25
fmt.Println(*p) // 输出: {Bob 25}
bannerAds