2 回答

TA貢獻1805條經驗 獲得超9個贊
如果你有匿名的、未命名的結構類型,那么如果你重復結構定義,你只能用復合文字初始化它們。這很不方便。
因此,請改用命名結構類型,這樣您就可以像這樣在復合文字中使用它們:
類型:
type domain struct {
? ? id string
}
type user struct {
? ? name? ? ?string
? ? domain? ?domain
? ? password string
}
type password struct {
? ? user user
}
type identity struct {
? ? methods? []string
? ? password password
}
type auth struct {
? ? identity identity
}
type tokenRequest struct {
? ? auth auth
}
req := &tokenRequest{
? ? auth: auth{
? ? ? ? identity: identity{
? ? ? ? ? ? methods: []string{"password"},
? ? ? ? ? ? password: password{
? ? ? ? ? ? ? ? user: user{
? ? ? ? ? ? ? ? ? ? name: os.Username,
? ? ? ? ? ? ? ? ? ? domain: domain{
? ? ? ? ? ? ? ? ? ? ? ? id: "default",
? ? ? ? ? ? ? ? ? ? },
? ? ? ? ? ? ? ? ? ? password: os.Password,
? ? ? ? ? ? ? ? },
? ? ? ? ? ? },
? ? ? ? },
? ? },
}

TA貢獻1871條經驗 獲得超13個贊
你可以,但你會打很多字:
package main
import (
"fmt"
"net/http"
)
type tokenRequest struct {
auth struct {
identity struct {
methods []string
password struct {
user struct {
name string
domain struct {
id string
}
password string
}
}
}
}
}
func main() {
s := tokenRequest{
auth: struct {
identity struct {
methods []string
password struct {
user struct {
name string
domain struct {
id string
}
password string
}
}
}
}{
identity: struct {
methods []string
password struct {
user struct {
name string
domain struct {
id string
}
password string
}
}
}{
methods: []string{http.MethodGet, http.MethodPost},
password: struct {
user struct {
name string
domain struct {
id string
}
password string
}
}{
user: struct {
name string
domain struct {
id string
}
password string
}{
name: "username",
domain: struct {
id string
}{
id: "domain id",
},
password: "password",
},
},
},
},
}
fmt.Printf("%+v\n", s)
}
你必須告訴 Go 你正在初始化什么類型的變量,所以你只需定義相同的匿名結構,每次緩慢但肯定地刪除一個級別。
出于這個原因,最好使用命名結構,這樣您就不必重復自己。
- 2 回答
- 0 關注
- 172 瀏覽
添加回答
舉報