英文:
Why am I getting an error when assigning a correct type?
问题
最近我开始尝试使用Go语言,但遇到了一些困难。我有以下类型定义:
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
字段吗?毕竟它只是一个字符串。
我在这里漏掉了什么?你能给我一点提示吗?
英文:
Recently I started experimenting with Go, but I hit on hard rock.
I have this type:
type LocationType string
const (
River LocationType = "River"
Mountain LocationType = "Mountain"
)
func (t LocationType) ToString() string {
return string(t)
}
I also have this one:
type LocationCreateInput struct {
Name string `json:"name,omitempty"`
Type *models.LocationType `json:"type,omitempty"`
}
Now I'm trying to create a new LocationCreateInput
variable:
input := &gqlModels.LocationCreateInput {
Name: "Test name",
Type: models.River
}
and I am getting the below error:
Cannot use 'models.Site' (type LocationType) as the type *models.LocationType
Can somebody point me to the right way of assigning the Type
value? In the end, it is just a string.
What am I missing here? Could you give me a push?
答案1
得分: 7
你正在尝试给指针类型赋值。所以它不仅仅是一个字符串,而是一个指向字符串的指针。
要么你将结构字段的类型从*models.LocationType
改为models.LocationType
,要么在赋值时需要取地址:
val := models.River
input := &gqlModels.LocationCreateInput{
Name: "测试名称",
Type: &val,
}
英文:
You are trying to assign a value to a pointer type. So it's not "just a string", it's a "a pointer to just a string".
Either you change the type of the struct field from *models.LocationType
to models.LocationType
, or you need to take the address when assigning:
val := models.River
input := &gqlModels.LocationCreateInput {
Name: "Test name",
Type: &val,
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论