可以使用以下两种方法初始化golang结构体:

  1. 使用结构体字面量
user := User{
    IsEncrypt: true,
    UserName: "John",
    Password: "secret",
    Online: true,
    AllowNamespaces: []struct {
        Namespace string `json:"namespace"`
        ReadOnly bool `json:"read_only"`
    }{
        {Namespace: "namespace1", ReadOnly: true},
        {Namespace: "namespace2", ReadOnly: false},
    },
}
  1. 使用结构体指针并使用&符号来取地址
user := &User{
    IsEncrypt: true,
    UserName: "John",
    Password: "secret",
    Online: true,
    AllowNamespaces: []struct {
        Namespace string `json:"namespace"`
        ReadOnly bool `json:"read_only"`
    }{
        {Namespace: "namespace1", ReadOnly: true},
        {Namespace: "namespace2", ReadOnly: false},
    },
}

注意,在第二种方法中,我们创建了一个指向User结构体的指针,并使用&符号将其地址赋值给user变量。

type-User-struct-ntIsEncrypt-------bool---jsonis_encryptntUserName--------string-jsonuser_namentPassword--------string-jsonpasswordntOnline----------bool---jsononlinentAllowNamespaces-struct-nttNamespace-string-jsonnamespacenttReadOnly--bool---jsonre

原文地址: https://www.cveoy.top/t/topic/qaG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录