gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:25:45 27 4
gpt4 key购买 nike

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

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

像这样:

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

我收到错误

expected identifier on left side of :=

但是,当我改成这个的时候

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

错误消失了! 为什么在 := 赋值中声明 k < n 个变量会失败?!

最佳答案

:= 不是 assignment , 它是一个 short variable declaration .分配使用例如简单的 = 运算符。

顾名思义:就是声明变量。 suite.db 不是一个变量,它是一个 expression ,更具体地说是 primary expression ;一个selector准确地说。

短变量声明使用语法:

ShortVarDecl = IdentifierList ":=" ExpressionList .

在哪里IdentifierList是:

IdentifierList = identifier { "," identifier } .

所以你必须列出identifiers .此“声明新变量规则”的一个“异常(exception)”是重新声明:

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.

因此,如果现有变量是在同一 block 中声明的,那么您可以在简短的变量声明中使用它们,并且您还提供了新的标识符(不仅仅是现有的标识符——在这种情况下,您将不得不使用赋值代替)。

参见相关:Why there are two ways of declaring variables in Go, what's the difference and which to use?

当您声明 err 之前并将 := 更改为 = 时,它起作用了,因为赋值不需要左边的标识符赋值运算符,但表达式:

Assignment = ExpressionList assign_op ExpressionList .

并且如上所述,suite.db 是一个表达式,就像现有变量(标识符)一样。

关于go - 为什么在 golang 中仅初始化定义中的一个变量会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52084687/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com