为什么在golang中仅初始化定义中的一个变量会失败 [英] Why does initializing just one variable in a definition fail, in golang

查看:51
本文介绍了为什么在golang中仅初始化定义中的一个变量会失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在调用具有以下签名的库函数时:

  func New()(* sql.DB,Sqlmock,错误) 

像这样:

  suite.db,suite.mock,err:= sqlmock.New()//在套件方法中 

我遇到错误

 位于:=左侧的预期标识符 

但是,当我更改为此

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

错误消失了!为什么声明k <:= 分配中的n个变量失败?!

解决方案

:= 不是短变量声明 .分配使用例如简单的 = 运算符.

顾名思义,它是声明变量. suite.db 不是变量,它是一个表达式,更多特别是主表达式;确切地说,是一个选择器.

简短变量声明使用以下语法:

  ShortVarDecl = IdentifierList:=" ExpressionList. 

IdentifierList 的位置是:

  IdentifierList =标识符{,"标识符}. 

因此,您必须列出标识符.重新声明:

是此声明新变量规则"的例外":

与常规变量声明不同,简短的变量声明可以重新声明,前提是它们最初是在相同类型的同一块中(如果该块是函数体,则在参数列表中)早先声明过,并且至少是非空白变量之一.因此,重新声明只能出现在多变量简短声明中.重新声明不会引入新的变量;只是为原始值分配了一个新值.

因此,如果在同一个块中声明了现有变量,则可以在短变量声明中使用它们,并且还提供了新的标识符(不仅是现有的标识符,在这种情况下,您必须使用赋值)./p>

请参阅相关内容: 解决方案

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

这篇关于为什么在golang中仅初始化定义中的一个变量会失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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