jjzjj

compiler-construction - if-else undefined variable 编译错误

coder 2024-07-06 原文

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

print(something)

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

如何避免这个编译错误,下个版本会修复吗?

最佳答案

在您的代码片段中,您定义了两个 something 变量,作用域为 if 语句的每个 block 。

相反,您需要一个作用域在 if 语句之外的变量:

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

print(something)

关于compiler-construction - if-else undefined variable 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18823657/

有关compiler-construction - if-else undefined variable 编译错误的更多相关文章

随机推荐