<p>Would it be possible to set the variables of a struct inside the struct like this </p>
<p>type car struct{
color string = red
engine string = “v8”
horsepower int = 330
} Is this possible ?</p>
<hr/>**评论:**<br/><br/>deusmetallum: <pre><p>No, you cannot do it like that. All variables are empty to start.</p>
<p>You would want to create a function for setting defaults, such as</p>
<pre><code>func NewCarWithDefaults() car {
....
</code></pre>
<p>}</p></pre>drakonka: <pre><p>This is how I've been doing it in my project; I'd be curious to find out if this is an accepted standard practice in Go or if there is a better approach.</p></pre>bastiaanvv: <pre><p>That is not possible. You can however do this if you declare a struct inline. I wouldn't use this for anything serious though.</p>
<pre><code>var example = struct {
name string
age int
}{
name: "John",
age: 13,
}
fmt.Println(example)
</code></pre>
<p>If you are trying to create a default value for your struct you could try this btw:</p>
<pre><code>func NewCar() *Car {
return &Car{
color: red,
engine: "v8",
horsepower: 330,
}
}
</code></pre></pre>agree-with-you: <pre><p>I agree, this does not seem possible.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传