Variable scope inside if statements

Slightly related to the question of variable scope, new gophers (go programmers) might find it interesting that you can also arbitrarily force variable scope with a pair of curly brackets { } anywhere in the code. You don't need a keyword for this.

Example:

// outside of scope
var color = "blue"

{
    // inside a new scope
    var color = "red"
    fmt.Println(color) // prints red
}

// outside of scope again
fmt.Println(color) // prints blue again

You can declare new1 before the if block and use make inside:

var new1 []string

if len(array1)>len(array2) {
    new1 = make([]string, 0, len(array1))
    // instructions ...
} else {
    new1 = make([]string, 0, len(array2))
    // other instructions ...
}

new2 := make([]string, 0, len(new1))
copy(new2, new1)

Tags:

Go