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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With