donte1234567 2018-08-29 19:20
浏览 440
已采纳

为什么在golang中仅初始化定义中的一个变量会失败

In calling a library function with the following signature:

func New() (*sql.DB, Sqlmock, error)

like this:

suite.db, suite.mock, err := sqlmock.New() // inside a suite method

I get error

expected identifier on left side of :=

However, when I change to this

var err error
suite.db, suite.mock, err = sqlmock.New()

the error disappears! Why does declaring k < n variables in a := assignment fail?!

  • 写回答

2条回答 默认 最新

  • dongzhouhao4316 2018-08-29 19:49
    关注

    := is not assignment, it is a short variable declaration. Assignment uses e.g. the simple = operator.

    As its name says: it is to declare variables. suite.db is not a variable, it is an expression, more specifically a primary expression; a selector to be exact.

    The short variable declaration uses the syntax:

    ShortVarDecl = IdentifierList ":=" ExpressionList .
    

    Where IdentifierList is:

    IdentifierList = identifier { "," identifier } .
    

    So you must list identifiers. One "exception" to this "declare new variables rule" is the redeclaration:

    Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.

    So you are allowed to use existing variables in a short variable declaration if they were declared in the same block, and you also provide new identifiers (not just existing ones–in which case you would have to use assignment instead).

    See related: Why there are two ways of declaring variables in Go, what's the difference and which to use?

    When you declare err prior and change := to = it works, because the assignment does not require identifiers on the left of the assignment operator, but expressions:

    Assignment = ExpressionList assign_op ExpressionList .
    

    And as detailed above, suite.db is an expression, just like existing variables (identifiers).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。