以下问题有多种答案/技巧:
如何将默认值设置为golang结构? 如何初始化结构在golang
我有几个答案,但还需要进一步讨论。
以下问题有多种答案/技巧:
如何将默认值设置为golang结构? 如何初始化结构在golang
我有几个答案,但还需要进一步讨论。
当前回答
对于Go结构体中的默认值,我们使用匿名结构:
Person := struct {
name string
age int
city string
}{
name: "Peter",
age: 21,
city: "Noida",
}
fmt.Println(人)
其他回答
一种可能的想法是编写单独的构造函数
//Something is the structure we work with
type Something struct {
Text string
DefaultText string
}
// NewSomething create new instance of Something
func NewSomething(text string) Something {
something := Something{}
something.Text = text
something.DefaultText = "default text"
return something
}
从https://golang.org/doc/effective_go.html # composite_literals:
有时0值还不够好,需要初始化构造函数,就像这个从包os派生的例子一样。
func NewFile(fd int, name string) *File {
if fd < 0 {
return nil
}
f := new(File)
f.fd = fd
f.name = name
f.dirinfo = nil
f.nepipe = 0
return f
}
type Config struct {
AWSRegion string `default:"us-west-2"`
}
对于Go结构体中的默认值,我们使用匿名结构:
Person := struct {
name string
age int
city string
}{
name: "Peter",
age: 21,
city: "Noida",
}
fmt.Println(人)
做这样的东西怎么样:
// Card is the structure we work with
type Card struct {
Html js.Value
DefaultText string `default:"html"` // this only works with strings
}
// Init is the main function that initiate the structure, and return it
func (c Card) Init() Card {
c.Html = Document.Call("createElement", "div")
return c
}
然后将其命名为:
c := new(Card).Init()