Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've just started learning Go today and have got stuck on variable scopes.

I've ultimately confused about how to get around the fact that I can't create a variable inside an if statement and the use it afterward.

This is my code. The problem is that new1 can't be created before the if statement because its size is dependent upon the result of the if statement, and by creating it inside the if statement I can't use it after the if statement ends.

if len(array1)>len(array2) {
    new1 := make([]string,0,len(array1))
    mc := Array2Map_string(array1)
    for _,tok :=range array2 {
        _, ok := mc[tok]
        if ok {
            new1[len(new1)]=tok
            }
        }
    } else {
    new1 := make([]string,0,len(array2))
    mc := Array2Map_string(array2)
    for _,tok :=range array1 {
        _, ok := mc[tok]
        if ok {
            new1[len(new1)]=tok
            }
        }
    }
new2 := make([]string,0,len(new1))
copy(new2, new1)

The only thing I can think of is to do something like

var pointlessvariable uint
if len(array1)>len(array2) {
pointlessvariable=len(array1)
} else {
pointlessvariable=len(array2)
}
var new1 = make([]string,0,pointlessvariable)
if len(array1)>len(array2) {
...

To be quite honest if that is truly the solution then I don't think I want to use Golang after all.

So what is the best way of solving this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...