速记回报 [英] Shorthand return

查看:47
本文介绍了速记回报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在Go 1.6或1.7中生成语法错误(语句末尾意外的++ ):

The following code generates a syntax error (unexpected ++ at end of statement) in Go 1.6 or 1.7:

package main

import "fmt"

var x int

func increment() int {
        return x++   // not allowed
}

func main() {
  fmt.Println( increment() )
}

这是不允许的吗?

推荐答案

这是一个错误,因为Go中的 ++ -是语句,而不是表达式:规范:IncDec语句(并且该语句没有将返回的结果).

It's an error, because the ++ and -- in Go are statements, not expressions: Spec: IncDec Statements (and statements have no results that would be returned).

有关推理的信息,请参阅Go常见问题解答:为什么++和-语句而不是表达式?为何使用后缀而不是前缀?

For reasoning, see Go FAQ: Why are ++ and -- statements and not expressions? And why postfix, not prefix?

如果不使用指针算法,则前缀和后缀增量运算符的便利性值会下降.通过将它们从表达式层次结构中完全删除,可以简化表达式语法,并且可以消除围绕++和-(考虑f(i ++)和p [i] = q [++ i])的求值顺序的混乱问题..简化意义重大.至于后缀与前缀,两者都可以正常工作,但后缀版本更为传统;带有STL的语言引起了对前缀的坚持,具有讽刺意味的是,该语言的名称包含后缀增量.

Without pointer arithmetic, the convenience value of pre- and postfix increment operators drops. By removing them from the expression hierarchy altogether, expression syntax is simplified and the messy issues around order of evaluation of ++ and -- (consider f(i++) and p[i] = q[++i]) are eliminated as well. The simplification is significant. As for postfix vs. prefix, either would work fine but the postfix version is more traditional; insistence on prefix arose with the STL, a library for a language whose name contains, ironically, a postfix increment.

所以您编写的代码只能写为:

So the code you wrote can only be written as:

func increment() int {
    x++
    return x
}

而且您必须在不传递任何内容的情况下调用它:

And you have to call it without passing anything:

fmt.Println(increment())

请注意,我们仍然会尝试使用赋值将其写在一行中,例如:

Note that we would be tempted to still try to write it in one line using an assignment, e.g.:

func increment() int {
    return x += 1 // Compile-time error!
}

但这在Go中也不起作用,因为分配也是一个声明,因此您会得到一个编译时错误:

But this also doesn't work in Go, because the assignment is also a statement, and thus you get a compile-time error:

语法错误:语句结尾出现意外的+ =

syntax error: unexpected += at end of statement

这篇关于速记回报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆