在结构中初始化字符串指针 [英] initialize string pointer in struct

查看:107
本文介绍了在结构中初始化字符串指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

转到新手问题:我正在尝试使用默认值初始化以下结构.我知道,如果"Uri"是一个字符串而不是一个指向字符串(* string)的指针,它将起作用.但是我需要这个指针来比较该结构的两个实例,如果未设置,则Uri将为nil.当我从json文件中整理内容时.但是,如何正确地将这样的结构初始化为静态默认值"?

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

上面的代码失败

cannot use "string" (type string) as type *string in field value

推荐答案

无法获得(指向)恒定值的地址,这就是初始化失败的原因.如果您定义了一个变量并传递了它的地址,那么您的示例将起作用.

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

这篇关于在结构中初始化字符串指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆