以下问题有多种答案/技巧:

如何将默认值设置为golang结构? 如何初始化结构在golang

我有几个答案,但还需要进一步讨论。


当前回答

type Config struct {
    AWSRegion                               string `default:"us-west-2"`
}

其他回答

一种可能的想法是编写单独的构造函数

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

对于Go结构体中的默认值,我们使用匿名结构:

Person := struct {
    name      string
    age       int
    city      string
}{
    name:      "Peter",
    age:        21,
    city:      "Noida",
}

fmt.Println(人)

Force a method to get the struct (the constructor way). From this post: A good design is to make your type unexported, but provide an exported constructor function like NewMyType() in which you can properly initialize your struct / type. Also return an interface type and not a concrete type, and the interface should contain everything others want to do with your value. And your concrete type must implement that interface of course. This can be done by simply making the type itself unexported. You can export the function NewSomething and even the fields Text and DefaultText, but just don't export the struct type something. Another way to customize it for you own module is by using a Config struct to set default values (Option 5 in the link). Not a good way though.

做这样的东西怎么样:

// 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()

其中一种方法是:

// declare a type
type A struct {
    Filed1 string
    Field2 map[string]interface{}
}

因此,每当你需要一个自定义类型的新变量时,只需调用NewA函数,你也可以将函数参数化,可选地将值分配给struct字段

func NewA() *A {
    return &A{
        Filed1: "",
        Field2: make(map[string]interface{}),
    }
}