3

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.

2
  • 5
    Honest advice: If you are "new in programming" you should basically never think about "optimization difference" of such trivia. Really. Never. Focus on correctness, sensible data structures and algorithms (which have way larger effect on runtime than any microoptimisation) and readability of your code. Commented Jan 23, 2019 at 7:43
  • golang.org/ref/spec#Declarations_and_scope Commented Jan 23, 2019 at 14:32

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.