<p>What are the objections with combining a getter and setter in a single method?</p>
<p>Example:</p>
<pre><code>// Name is both a getter and setter to the name property.
func (p *Person) Name(value ...string) string {
if len(value) > 0 {
p.name = strings.Title(value[len(value)-1])
}
return p.name
}
func ExampleGetSet() {
p := &Person{name: "marie"}
p.Name("anna")
name := p.Name()
fmt.Println(name)
// Output: Anna
}
</code></pre>
<p><a href="https://gist.github.com/namsral/c4ed7aa6650221146cd1faa8c5ac9748" rel="nofollow">gistgithub.com</a></p>
<hr/>**评论:**<br/><br/>k_u_r_o_k_u_s_e: <pre><p>this is not idiomatic,that's all; someone else pointed effective Go guide, you should follow it, that's a strict minimum.</p>
<p>for a property prop , your getter should be called Prop()T and your setter SetProp(T) .</p></pre>metamatic: <pre><p>I get the impression that getters and setters aren't encouraged much at all in Go. For example, look at how many directly exposed fields there are in the http part of stdlib.</p></pre>k_u_r_o_k_u_s_e: <pre><p>Yeah, the thing is the std lib has quite a few problems IHMO but was never refactored because of compatibility issues. Using Getters and Setters allows "uniform message passing" and also replacing concrete types with interfaces in function parameters. I think it is a good practice, in general. I mean it's like factories. Should people write factories or create values by declaring structs ? I believe in strict encapsulation which allows efficient refactoring. But if a struct has no method or is a "bean" ( data transfer object), then struct declaration is preferable. </p></pre>dchapes: <pre><blockquote>
<p>Clear is better than clever.<br/>
-- <a href="https://go-proverbs.github.io/" rel="nofollow">Go Proverbs</a></p>
</blockquote>
<p><code>p.SetName("anna")</code> is clear, abusing variadic paramaters is not (and IMHO it's not very clever). And what about someone that does <code>p.Name("anna", "WTF?!")</code>; compiler type checking and function/method signature checking is a good thing.</p></pre>RalphCorderoy: <pre><p>Relevant to the conversation: <a href="https://golang.org/doc/effective_go.html#Getters" rel="nofollow">https://golang.org/doc/effective_go.html#Getters</a>.</p></pre>madman2233: <pre><p>Seems redundant getting a return of the same thing your setting. Might be more useful if you returned the old value if you set a new one.</p></pre>cfsalguero: <pre><p>It is not bad. It is not Go idiomatic, it is Perl idiomatic: <a href="http://docstore.mik.ua/orelly/perl4/porm/ch09_13.htm" rel="nofollow">http://docstore.mik.ua/orelly/perl4/porm/ch09_13.htm</a></p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传