dourun2990 2015-11-01 02:09 采纳率: 100%
浏览 21
已采纳

去可变范围和阴影

This is an example from GOPL - "The expressions x[i] and x + 'A' - 'a' each refer to a declaration of x from an outer block; we'll explain this in a moment."

The explanation never comes. Why is x[i] referring to the x in the outer scope? As soon as you redeclare x in an inner block it should shadow the x in the outer block. Why does this work?

package main

import "fmt"

func main() {
    x := "hello!"
    for i := 0; i < len(x); i++ {
        x := x[i]
        if x != '!' {
            x := x + 'A' - 'a'
            fmt.Printf("%c", x)
        }
    }
}

http://play.golang.org/p/NQxfkTeGzA

  • 写回答

1条回答 默认 最新

  • dongyinzheng6572 2015-11-01 04:18
    关注

    := operator creates a new variable and assigns the right hand side value to it.

    At the first iteration of the for loop, in the step x := x[i], the only x the right hand side sees is the x defined in the step x := "hello!". As far as the right hand side sees x is not redeclared yet.

    As soon as you redeclare x in an inner block..

    It is not yet. Its redeclared only after x := x[i].

    And at the end of the iteration the new x's scope ends. It is not reused in a new iteration.

    When a new iteration happens its the same thing all over again.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 反编译微信小游戏求指导
  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?
  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题