go - 速记返回

标签 go shorthand

以下代码在 Go 1.6 或 1.7 中会产生一个语法错误(unexpected++ at end of statement):

package main

import "fmt"

var x int

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

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

这不应该被允许吗?

最佳答案

这是一个错误,因为 Go 中的 ++-- 是语句,而不是表达式:Spec: IncDec Statements (并且语句没有可返回的结果)。

有关推理,请参阅 Go FAQ:Why are ++ and -- statements and not expressions? And why postfix, not prefix?

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.

所以你写的代码只能写成:

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

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

fmt.Println(increment())

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

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

但这在 Go 中也不起作用,因为 assignment也是一个语句,因此你会得到一个编译时错误:

syntax error: unexpected += at end of statement

关于go - 速记返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39280447/

相关文章:

http - beego POST 请求体始终为空

go - 如何使用包管理器,gopm

php - 速记 switch 语句是否存在(在 PHP 中)?

css - 速记 CSS 与普通 CSS 不同

javascript - 用于反转 bool 值的简写赋值运算符

javascript - 这个简写更聪明

go - 是否可以使用GoLang调试预构建的go可执行文件?

dictionary - golang有支持集合数据结构的计划吗?

go - 如何使用它的客户端查看 kubernetes 事件详细信息?