doudao3170 2014-06-29 10:22
浏览 86
已采纳

if语句中的变量范围

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?

  • 写回答

1条回答 默认 最新

  • dsfsfsfsfs55656 2014-06-29 10:30
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊