Golang:if语句中的变量范围 [英] Golang: variable scope inside if statements

查看:201
本文介绍了Golang:if语句中的变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我最终对如何解决这个事实感到困惑,因为我可以' t在if语句中创建一个变量并在之后使用它。



这是我的代码。问题是new1不能在if语句之前创建,因为它的大小取决于if语句的结果,并且通过在if语句中创建它,我不能在if语句结束后使用它。

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

我唯一能想到的就是做一些类似于

  var pointlessvariable u如果len(array1)> len(array2){
pointlessvariable = len(array1)
} else {
pointlessvariable = len(array2)
} $ int
b $ b var new1 = make([] string,0,pointlessvariable)
如果len(array1)> len(array2){
...

说实话,如果这真的是解决方案,那么我认为我不想使用Golang。



那么解决这个问题的最好方法是什么?

解决方案

您可以声明 new1 if 块之前,并在内部使用 make

  var new1 []字符串
$ b $如果len(array1)> len(array2){
new1 = make ([] string,0,len(array1))
//指令...
} else {
new1 = make([] string,0,len(array2))
//其他指令...
}

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


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?

解决方案

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)

这篇关于Golang:if语句中的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆