当您分配正确的类型时,为什么会出现错误?

huangapple go评论78阅读模式
英文:

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,
}

huangapple
  • 本文由 发表于 2021年8月3日 20:32:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/68636114.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定