英文:
Short-declaration operator shadows global variable
问题
有一个名为oneFunction的函数,返回类型为int和error的两个值。
我想将第一个值赋给已经存在的变量,并将第二个值赋给一个新变量。
如果我使用短声明运算符:=,将会创建两个新变量x和err。
var x int
x, err := oneFunction()
为了避免创建新的x变量,我不能使用:=运算符,并且在调用oneFunction之前声明err。
var x int
var err error
glob, err = oneFunction()
我想知道是否有其他方法将第一个值设置为全局变量,而不是创建一个新的变量?
英文:
There is oneFunction that returns 2 values of types int and error.
I want to assign the first value to already existing variable and assign second value to a new variable.
If I use short declaration operator :=, there will be created 2 new variables x and err.
var x int
x, err := oneFunction()
To get rid of creating new x variable I must not use := operator and declare err before calling oneFunction
var x int
var err error
glob, err = oneFunction()
I'd like to know if there is another way to set first value to global variable instead of creating a new one?
答案1
得分: 1
不。声明 var err error 的示例是实现你想要的方式。
英文:
No. Your example that declares var err error is the idiomatic way to do what you want.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论