doutang2017 2017-10-26 15:00
浏览 57

重新声明的变量未使用

This code compiles:

func (wc *WordCounter) Write(buf []byte) (int, error) {
    for adv, i := 0, 0; i < len(buf); i += adv {
        adv, _, _ = bufio.ScanWords(buf[i:], true)
        *wc++
    }
    return len(buf), nil
}

But the following does not compile. Notice the short declaration adv, token, _ := .. where I expected that adv would be redeclared (as opposed to be declared as a new var):

func (wc *WordCounter) Write(buf []byte) (int, error) {
    for adv, i := 0, 0; i < len(buf); i += adv {
        // error: adv declared and not used
        adv, token, _ := bufio.ScanWords(buf[i:], true) 
        fmt.Println(string(token))
        *wc++
    }
    return len(buf), nil
}

According to the Go spec:

a short variable declaration may redeclare variables provided they were originally declared earlier in the same block. [...] Redeclaration does not introduce a new variable; it just assigns a new value to the original.

I guess this means that the for statement is a block in and of itself, and that adv therefore is considered to be declared over again (as opposed to being redeclared) in the for body?

  • 写回答

2条回答 默认 最新

  • doushiposong30622 2017-10-26 16:12
    关注

    This is working as intended. Consider the following:

    https://play.golang.org/p/cyJZgM5QYn

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        for i := 0; i < 10; i++ {
            fmt.Printf("%p", &i)
            i := i
            fmt.Printf(" | %p
    ", &i)
        }
    }
    

    Variables you declare within the for loop header are defined for the entire for loop. The first i printed in the above has the same address on every single iteration. On the other hand, variables declared inside the loop itself are local only to that iteration of the loop! Note that the second i printed on each line has a unique address, as a new variable is being created on each iteration. This makes the lifetime of the two variables, and thus their scopes, different. Since they exist in separate scopes, the inner scope can (usually inadvertently) shadow the outer scope variable via the short-form declaration.

    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法