doubian19900911 2016-02-04 22:50
浏览 136
已采纳

在Go if语句中混合:=和=

Go has a common idiom that looks like this:

if val, err := func(); err != nil {
    /* val and err are in scope */
...
}
/* val and err are no longer in scope */

using "short assignment". I'm certainly a fan. It feels similar to doing:

/* code not involving val */
{
    int val;

    if ((val = func()) == ERR_VALUE) {
        /* Process the error */
    }
    /* Do something with val */
}
/* more code not involving val */

in C++. What trips me up is that, in the case where there is more than one variable in the first clause of the if, they have to have the same scope, i.e. you have to do either:

var err error
var val string

if val, err = func(); err != nil {
...

or

if val, err := func(); err != nil {
...

A very common use case would seem to be where you have a variable that you'd like to set in the first clause of the if, test for an error, and if there is none, continue with the rest of the program flow (and be able to use whatever values you assigned in executing the if). But, it seems to me, if you want to do that, you have to either:

  1. Use a temporary variable, and then assign the persistent variable value inside an else:

    var val
    
    if tempval, err := func(); err != nil {
        /* Process the error */
    } else {
        val = tempval
    }
    
  2. Declare the err variable with scope that extends past the if, as above.

The first option seems clunky - being forced to use an "else" clause just to make sure that the value doesn't fall out of scope - and the second throws away the advantages of limiting the scope of the variables. What idioms do more experienced Go programmers use for this (seemingly very common) situation?

  • 写回答

1条回答 默认 最新

  • dsfds4551 2016-02-04 22:54
    关注

    The Go Programming Language Specification

    If statements

    "If" statements specify the conditional execution of two branches according to the value of a boolean expression. If the expression evaluates to true, the "if" branch is executed, otherwise, if present, the "else" branch is executed.

    IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] .
    

    .

    if x > max {
      x = max
    }
    

    The expression may be preceded by a simple statement, which executes before the expression is evaluated.

    if x := f(); x < y {
      return x
    } else if x > z {
      return z
    } else {
      return y
    }
    

    If you can't take advantage of the special form,

    if val, err := fnc(); err != nil {
        // ...
    }
    

    then use the regular form,

    val, err := fnc()
    if err != nil {
        // ... 
    }
    

    The regular form is the Go language necessary and usual form. The special form is a specialization, for convenience, of the regular form; it's not necessary. If the special form is more convenient to use than the regular form, use it. Otherwise, use the regular form.


    Go is a block-structured programming language tracing it's ancestry back to Algol 60, C, Pascal, Modula 2, and Oberon.

    The Go Programming Language Specification

    Blocks

    Declarations and scope

    Therefore, you can write

    x := false
    {
        x := true
        if x {
            fmt.Println(x)
        }
    }
    fmt.Println(x)
    

    or, equivalently, as a convenience,

    x := false
    if x := true; x {
        fmt.Println(x)
    }
    fmt.Println(x)
    

    The output in both cases is

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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化