<p>I'm a newbie to Go (coming from Java). I was surprised to see that Go doesn't have a <a href="https://en.wikipedia.org/wiki/%3F:" rel="nofollow">ternary operator</a>. The <a href="https://golang.org/doc/faq#Does_Go_have_a_ternary_form" rel="nofollow">FAQ</a> just says that Go doesn't have :?, then says that you can use the standard if-else chain to achieve it.</p>
<p>I understand that not using :? might improve readability, but it's still really neat! So why was it left out? And should Go have it? What do you guys think?</p>
<hr/>**评论:**<br/><br/>dgryski: <pre><p>My favourite arguments against the ternary operator is:</p>
<p><code>int median(int[5] a){
return a[a[0]<a[1]?a[2]<a[3]?a[0]<a[2]?a[1]<a[4]?a[1]<a[2]?a[2]<a[4]?2:4:a[1]<a[3]?1:3:a[2]<a[4]?a[3]<a[4]?3:4:a[1]<a[2]?1:2:a[3]<a[4]?a[0]<a[3]?a[1]<a[3]?1:3:a[0]<a[4]?0:4:a[0]<a[4]?a[1]<a[4]?1:4:a[0]<a[3]?0:3:a[0]<a[3]?a[1]<a[4]?a[1]<a[3]?a[3]<a[4]?3:4:a[1]<a[2]?1:2:a[3]<a[4]?a[2]<a[4]?2:4:a[1]<a[3]?1:3:a[2]<a[4]?a[0]<a[2]?a[1]<a[2]?1:2:a[0]<a[4]?0:4:a[0]<a[4]?a[1]<a[4]?1:4:a[0]<a[2]?0:2:a[2]<a[3]?a[0]<a[3]?a[2]<a[4]?a[0]<a[4]?a[0]<a[2]?2:0:a[1]<a[4]?4:1:a[0]<a[2]?a[0]<a[4]?4:0:a[1]<a[2]?2:1:a[1]<a[4]?a[3]<a[4]?a[1]<a[3]?3:1:a[2]<a[4]?4:2:a[1]<a[3]?a[1]<a[2]?2:1:a[3]<a[4]?4:3:a[0]<a[2]?a[3]<a[4]?a[0]<a[4]?a[0]<a[3]?3:0:a[1]<a[4]?4:1:a[0]<a[3]?a[0]<a[4]?4:0:a[1]<a[3]?3:1:a[1]<a[4]?a[2]<a[4]?a[1]<a[2]?2:1:a[3]<a[4]?4:3:a[1]<a[2]?a[1]<a[3]?3:1:a[2]<a[4]?4:2];
}
</code></p>
<p>I saw this code proposed in total seriousness in a programming language discussion thread.</p></pre>RalphCorderoy: <pre><p>Other arguments aside, the grammar <em>could</em> stop that happening by allowing only one use.</p></pre>drvd: <pre><p>A simple ?: is neat and useful.</p>
<p>But there is no (sensible) way to prevent ugly nesting:</p>
<pre><code>(foo() ? a() : b()) ? (bar() ? 7 : -1) : wuz() ? g() : 8
</code></pre>
<p>Which doesn't simply hurts readability, it kills it. </p></pre>1-21Gigawatts: <pre><p>I've only ever used it in moderation, so I didn't consider that people would nest ?: inside of ?: inside of...</p>
<p>Yeah, that makes sense.</p></pre>CaffeineComa: <pre><p>Wow, good point. I used to wonder the same thing as OP, since the judicious use of ternary is a good way to cut down on LoC and (IMHO) actually make code short and readable. But it never really occurred to me that someone would abuse it in the way you outlined. I wonder if it's possible for some future version of the Go compiler to only allow a "single level" of ternary.</p></pre>natefinch: <pre><p>We had a critical security bug in production for years at my last job because of a misused ternary that never would have happened if someone had just used an if statement. I'm happy it doesn't exist in go, even if it makes some things a little bit more verbose.</p></pre>tmornini: <pre><p>If the tests were complete...</p>
<p>I'm confident the ternary operator was cut in favor of minimalism, not due to a belief or actual evidence that it increases bug rates...</p></pre>NichtMitCommander: <pre><p>Not having a ternary operator is a feature of Go that I am happy about, especially if I have to read other peoples code.</p></pre>Ainar-G: <pre><p>Here is an example (from Toonz source code) that shows why ternary operator may be a bad idea:</p>
<pre><code>void rgb_to_lightness_(
const double re, const double gr, const double bl, double &li)
{
li=((re < gr) ? ((gr < bl) ? bl : gr) : ((re < bl) ? bl : re) +
(gr < re)
? ((bl < gr) ? bl : gr)
: ((bl < re) ? bl : re)) / 2.0;
}
</code></pre></pre>weberc2: <pre><p>I think the philosophy regarding readability in Go is that 'explicit' is more readable than 'terse'. Especially when supporting 'terse' adds complexity to the parser.</p></pre>MrSaints: <pre><p>"The" C-like ternary operator was not included because of readability issues, and it's pretty easy to abuse. I'm personally apathetic about it. I don't think it'll add a lot of value.</p>
<p>BTW, Go does have ternary operators (not "the" conditional expression though). e.g. <code>s, ok := v.(string)</code></p></pre>velco: <pre><p>The only expression in this snippet is the type assertion, which has one operand.</p>
<p>"n-ary operator" means "with n operands"</p></pre>MrSaints: <pre><p>By your last statement, that snippet is indeed an example of a ternary operator in Go (albeit, not the one that most languages, and people have been accustomed to, "the" ?: one). It is an assignment operator (in the context of a type assertion) which has 3 operands. Go is filled with left-associative ternary operators.</p></pre>velco: <pre><p>No. The only operand is <code>v</code>. The operation is "type assertion to <code>string</code>"; The type <code>string</code> is (arguably) not an operand, as you can't place a variable there.
The variables <code>s</code> and <code>ok</code> are not <em>operands</em>, they are the <em>results</em> of the operation.
And assignment is not an operator in Go, as the assignment in Go is not an expression.</p></pre>MrSaints: <pre><p>I can see where you're coming from, but you seem really misinformed.</p>
<blockquote>
<p>s and ok are not operands, they are the results of the operation</p>
</blockquote>
<p>Based on the <a href="https://golang.org/ref/spec#identifier" rel="nofollow">specs</a>, they are indeed operands. And it makes explicit <a href="https://golang.org/ref/spec#Assignments" rel="nofollow">references</a> to them, e.g.</p>
<ul>
<li>"The blank identifier may appear as an operand only on the left-hand side of an assignment."</li>
<li>"The right hand operand is a single multi-valued expression such as a function call, a channel or map operation, or a type assertion. The number of operands on the left hand side must match the number of values."</li>
<li>"When evaluating the operands of an expression, assignment, or return statement, all function calls, method calls, and communication operations are evaluated in lexical left-to-right order."</li>
</ul>
<blockquote>
<p>And assignment is not an operator in Go, as the assignment in Go is not an expression.</p>
</blockquote>
<p>I'd like to know where you learnt that. Unless I've misunderstood what you're saying, you're suggesting that an <a href="https://en.wikipedia.org/wiki/Operator_(computer_programming" rel="nofollow">operator</a>) ("More involved examples include assignment (usually = or :=)") is not an operator unless it's an expression.</p>
<p>The two are not equivalent as indeed, "an expression specifies the computation of a value by applying operators and functions to operands."</p>
<p>Anyway, I think this is starting to become a fruitless contention over semantics, and you don't have to take <a href="https://groups.google.com/d/msg/golang-nuts/w1dPeHFSp9g/wxhKsQheQ7UJ" rel="nofollow">my word</a> for it.</p></pre>velco: <pre><p>This <a href="https://golang.org/ref/spec#Operators" rel="nofollow">https://golang.org/ref/spec#Operators</a> is the complete list of operators in Go. Neither of them has three or more operands.</p>
<p>I will agree that not only expressions can have operands.</p>
<p>And something that Mr.Pike says is true, is not true just because Mr.Pike says it.
Of course, you're completely free to rely on authority, rather than logic.</p></pre>MrSaints: <pre><p>I'm relying on your original statement that <code>"n-ary operator" means "with n operands"</code>, and from my understanding, it fits the logic (FYI, the <a href="https://github.com/golang/go/blob/master/src/go/token/token.go#L70" rel="nofollow">tokenizer</a> considers it an operator).. But yea, agree to disagree.</p></pre>Tasssadar: <pre><p>I really don't know about readability. For me, this...</p>
<pre><code>func (d *decoder) decodeHttps(s *tcpStream, t time.Time) {
prefix := s.dstPort == 443 ? HttpsRequest : HttpsResponse
if s.reported || !d.dumpTcpBlockStart(s, t, prefix) {
return
}
s.reported = true
fmt.Fprintf(d.out, "\n")
}
</code></pre>
<p>..is much more readable than this: </p>
<pre><code>func (d *decoder) decodeHttps(s *tcpStream, t time.Time) {
var prefix = HttpsRequest
if s.dstPort == 443 {
prefix = HttpsResponse
}
if s.reported || !d.dumpTcpBlockStart(s, t, prefix) {
return
}
s.reported = true
fmt.Fprintf(d.out, "\n")
}
</code></pre>
<p>or even this:</p>
<pre><code>func (d *decoder) decodeHttps(s *tcpStream, t time.Time) {
var prefix string
if s.dstPort == 443 {
prefix = HttpsResponse
} else {
prefix = HttpRequest
}
if s.reported || !d.dumpTcpBlockStart(s, t, prefix) {
return
}
s.reported = true
fmt.Fprintf(d.out, "\n")
}
</code></pre>
<p>...like, you just made me read 3-4 more lines and extra indentation level for something so simple. Why.</p>
<p>Yes, it is extremely easy to abuse<sup><sup>don't,</sup></sup> <sup><sup>then?</sup></sup> . So is goto, and it is present in golang in properly limited form.</p>
<p>With that said, I have no idea how difficult is it to add to golang compiler - if it would add a lot of unnecessary clutter, then I'm all for omitting it.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传