<p><strong>Real case example</strong></p>
<p>I have a function <code>biomeCategorization(s string) (float64, string){...}</code> which returns a <code>float64</code> and a <code>string</code> which I'd like to assign in a one shot as values for the key fields <code>temperature</code> and <code>climateZone</code> of my struct.</p>
<p>With the current code go vet reports <code>.\main.go:61:4: mixture of field:value and value initializers</code> for the line <code>temperature, climateZone: biomeCategorization(f.Name())</code></p>
<pre><code> for _, f := range files {
// Add the biomes found to the biomeList map
biomeList[f.Name()] = append(biomeList[f.Name()], biome{
name: f.Name(),
temperature, climateZone: biomeCategorization(f.Name()),
})
}
</code></pre>
<p><strong>Minimal environment code</strong></p>
<p><a href="https://play.golang.org/p/M8kQd92ukIN" rel="nofollow">Here</a> is a sample play code I set up as a minimal environment</p>
<p>I've tried to google a bit and browse stack overflow without success, if anyone one finds results online please tell me which keyword\query you used.</p>
<hr/>**评论:**<br/><br/>MuffinSoma: <pre><p>I don't think there's a syntax that allows you to do that. Ignoring concerns about optimization, you'd need to use a temporary variable to implement that, e.g.</p>
<pre><code>b := biome{name: f.Name()}
b.temperature, b.climateZone = biomeCategorization(b.name)
biomeList[b.name] = append(biomeList[b.name], b)
</code></pre>
<p>However, the most straightforward fix here would be to make <code>biomeCategorization</code> return a <code>biome</code> type instead. It already has the values needed to fill it out. This is assuming, of course, that the real code doesn't have additional complications.</p></pre>Maxiride: <pre><p>Ok, thank you very much for the insight. Returning a biome type with those fields filled works perfectly (as suggested by <a href="https://www.reddit.com/user/Scott_Draper" rel="nofollow">Scott_Draper</a> too).</p>
<p>I was more concerned about not knowing a proper syntax for this ^^</p></pre>Scott_Draper: <pre><p>It would be more elegant to just return a biome struct from biomeCategorization.</p></pre>hell_0n_wheel: <pre><p>A statement like this is meaningless without context. Usability, maintainability trumps elegance every time.</p></pre>Scott_Draper: <pre><p>Usability and maintainability all contribute to elegance.</p></pre>klaidliadon: <pre><p>It's not possible to assign multiple values returned from a function to struct fields.</p>
<p>You are forced to assign them to some variables, then you can use in the struct.<br/>
<a href="https://play.golang.org/p/RpU2GfxwnKg" rel="nofollow">https://play.golang.org/p/RpU2GfxwnKg</a></p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传