Golang遮蔽行为说明 [英] Golang shadowing behavior explanation

查看:59
本文介绍了Golang遮蔽行为说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此片段中

    list := []string{"a", "b", "c"}
    for {
        list := repeat(list)
...

    func repeat(list []string) []string {
...

很明显,用作 repeat()函数参数的 list 变量是外部的,阴影列表变量.现在我的问题是,Go语言律师将如何解释这种行为?乍一看,我认为内部列表变量的声明应该在 repeat(list)表达式求值之前.

it is clear that list variable used as the argument to repeat() function is the outer, shadowed list variable. Now my question is, how would a Go language lawyer explain this behaviour? At first glance, I thought the declaration of the inner list variable would have preceded the repeat(list) expression evaluation.

推荐答案

Go的词法范围是使用块.在此示例中:

list := []string{"a", "b", "c"}
for {
    list := repeat(list)

第二个 list 遮盖了for块中的第一个,并且不会更改外部的 list 变量.

The second list shadows the first within the for block, and doesn't alter the outer list variable.

因为在声明和分配内部列表之前先评估 repeat 的参数,所以 repeat 从外部接收值列表

Because the arguments to repeat are evaluated before the inner list is declared and assigned, repeat receives the value from the outer list

这篇关于Golang遮蔽行为说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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