如果-否则未定义变量编译错误

huangapple go评论66阅读模式
英文:

if-else undefined variable compile error

问题

在这个代码示例中,编译器会报一个undefined: something的错误。由于这是一个if else语句,something变量将在运行时定义,但编译器无法检测到这一点。

你可以如何避免这个编译错误?这个问题在下一个版本中会被修复吗?

英文:
if someCondition() {
    something := getSomething()
} else {
    something := getSomethingElse()
} 

print(something)

in this code example, compiler gives an undefined: something error. Since this is an if else statement something variable will be defined in the runtime, but compiler fails detect this.

How can I avoid this compile error, also will this be fixed in the next versions?

答案1

得分: 1

两个 something 变量是具有不同作用域的两个不同变量。它们在 if/else 块作用域之外不存在,这就是为什么会出现未定义错误。

你需要在 if 语句之外定义该变量,可以像这样:

var something string

if someCondition() {
    something = getSomething()
} else {
    something = getSomethingElse()
} 

print(something)
英文:

The two something variables are two different variables with different scopes. They do not exist outside the if/else block scope which is why you get an undefined error.

You need to define the variable outside the if statement with something like this:

var something string

if someCondition() {
    something = getSomething()
} else {
    something = getSomethingElse()
} 

print(something)

答案2

得分: 1

在你的代码片段中,你定义了两个 something 变量,它们的作用域限定在 if 语句的每个块内。

相反,你想要一个作用域在 if 语句之外的单个变量:

var something sometype
if someCondition() {
    something = getSomething()
} else {
    something = getSomethingElse()
} 

print(something)
英文:

In your code fragment, you're defining two something variables scoped to each block of the if statement.

Instead, you want a single variable scoped outside of the if statement:

var something sometype
if someCondition() {
    something = getSomething()
} else {
    something = getSomethingElse()
} 

print(something)

huangapple
  • 本文由 发表于 2013年9月16日 16:35:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/18823657.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定