英文:
initialize string pointer in struct
问题
Go新手问题:我正在尝试初始化以下结构体,并设置默认值。我知道如果"Uri"是一个字符串而不是指向字符串的指针(*string),它是可以工作的。但是我需要这个指针来比较两个结构体的实例,其中如果未设置Uri,则Uri将为nil,例如当我从JSON文件解组内容时。但是如何正确地初始化这样一个"静态默认"结构体呢?
type Config struct {
Uri *string
}
func init() {
var config = Config{ Uri: "my:default" }
}
上面的代码会失败,显示错误信息:
cannot use "string" (type string) as type *string in field value
英文:
Go Newbie question: I am trying to init the following struct, with a default value. I know that it works if "Uri" is a string and not pointer to a string (*string). But i need this pointer for comparing two instances of the struct, where Uri would be nil if not set, e.g. when i demarshal content from a json file. But how can I initialize such a struct properly as a "static default"?
type Config struct {
Uri *string
}
func init() {
var config = Config{ Uri: "my:default" }
}
The code above fails with
cannot use "string" (type string) as type *string in field value
答案1
得分: 89
无法获取常量值的地址(指向),这就是为什么你的初始化失败的原因。如果你定义一个变量并传递它的地址,你的示例将会工作。
type Config struct {
Uri *string
}
func init() {
v := "my:default"
var config = Config{ Uri: &v }
}
英文:
It's not possible to get the address (to point) of a constant value, which is why your initialization fails. If you define a variable and pass its address, your example will work.
type Config struct {
Uri *string
}
func init() {
v := "my:default"
var config = Config{ Uri: &v }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论