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 关注
- 134 浏览
添加回答
举报