dongpan1416 2016-09-01 20:34
浏览 25
已采纳

Go(golang)中的速记返回

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() )
}

Shouldn't this be permitted?

  • 写回答

1条回答 默认 最新

  • dounai1986 2016-09-01 20:37
    关注

    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).

    For reasoning, see 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.

    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!
    }
    

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动