Search code examples
go

if-else undefined variable compile error


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?


Solution

  • 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)