Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go Declare Variable outside vs Declare Variable Inside Loop

Tags:

go

I am a new in programming. I have two examples code in Go and its about loop using range. This is the first example:

Program A

type Test struct {
    Text string
}

func main() {
    tests := []Test{
        Test{"Test1"},
        Test{"Test2"},
    }

    var a Test
    for _, test := range tests {
        a = test
        fmt.Println(a)
    }
}

This is the second example:

Program B

type Test struct {
    Text string
}

func main() {
    tests := []Test{
        Test{"Test1"},
        Test{"Test2"},
    }

    for _, test := range tests {
        a := test
        fmt.Println(a)
    }
}

In the first example 'a' is declared outside the loop, but in the second example 'a' is declared inside the loop. Like in the other programming language, what is the difference between two example program? Is there any optimization difference? Thank you.

like image 655
dev-x Avatar asked Jul 01 '26 14:07

dev-x


1 Answers

The variables have different scopes. It is usually best practice to use the smallest scope possible as in the second example.

There should be no optimization difference.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!