为什么在分配正确的类型时出现错误?
最近我开始尝试围棋,但我遇到了硬摇滚。我有这种类型:
type LocationType string
const (
River LocationType = "River"
Mountain LocationType = "Mountain"
)
func (t LocationType) ToString() string {
return string(t)
}
我也有这个:
type LocationCreateInput struct {
Name string `json:"name,omitempty"`
Type *models.LocationType `json:"type,omitempty"`
}
现在我正在尝试创建一个新LocationCreateInput变量:
input := &gqlModels.LocationCreateInput {
Name: "Test name",
Type: models.River
}
我收到以下错误:
Cannot use 'models.Site' (type LocationType) as the type *models.LocationType
有人可以指出我分配Type价值的正确方法吗?最后,它只是一个字符串。
我在这里缺少什么?你能给我推一下吗?
回答
您正在尝试为指针类型赋值。所以它不是“只是一个字符串”,而是一个“指向一个字符串的指针”。
要么将 struct 字段的类型从*models.LocationTypeto更改为models.LocationType,要么在分配时需要取地址:
val := models.River
input := &gqlModels.LocationCreateInput {
Name: "Test name",
Type: &val,
}
- @Slim:你不能取常量的地址