How to set variables inside struct

agolangf · · 405 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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&#39;ve been doing it in my project; I&#39;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&#39;t use this for anything serious though.</p> <pre><code>var example = struct { name string age int }{ name: &#34;John&#34;, 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 &amp;Car{ color: red, engine: &#34;v8&#34;, horsepower: 330, } } </code></pre></pre>agree-with-you: <pre><p>I agree, this does not seem possible.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

405 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传