go - Go中的简短声明

标签 go

我正在学习Go,但我不明白代码是如何允许我重新声明相同的变量“手机”的。我以为您只能在函数作用域内短暂声明一个变量,然后才可以在使用它声明新变量时重新声明该变量。但是,使用下面的代码,我可以在两次short-declare语句中两次声明“手机”,而无需声明新变量。

package main

import "fmt"

func main() {
    phones := map[string]string{
        "bowen": "202-555-0179",
        "dulin": "03.37.77.63.06",
        "greco": "03489940240",
    }

    multiPhones := map[string][]string{
        "bowen": {"202-555-0179"},
        "dulin": {"03.37.77.63.06", "03.37.70.50.05", "02.20.40.10.04"},
        "greco": {"03489940240", "03489900120"},
    }

  fmt.Println(phones)

  who, phone := "greco", "N/A"
  if phones := multiPhones[who]; len(phones) >= 2 {
    fmt.Println(phones)
    phone = phones[1]
  }

  fmt.Printf("%s's 2nd phone number: %s\n", who, phone)
}

最佳答案

Go不允许在相同范围内重新定义变量。
您拥有的代码包含两个不同范围的变量。
Go中允许这样做。这不成问题。
您的代码类似于:

func main() { 
    name := "adam"
    if name := true; name != false {   // the var name here is in if scope.
 
        fmt.Println("name in if scope is :", name)
    }

    fmt.Println("name out if scope is : ", name)
    
    // name := "jawad" this is error. redifined in same scope not allowed.
}

关于go - Go中的简短声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65643380/

相关文章:

go - golang 基准测试可以提供自定义输出吗?

ssh - 使用 SSH 和使用 golang 的 pem/key 连接到服务器

go - beego 必须有一个寄存器 DataBase 别名 `default`

go: 在 select 和 break 中过滤事件

go - 使用数组符号在 GoLang 中声明接口(interface)

go - 新手 : Properly sizing a []byte size in GO (Chunking)

go - 如何通过从另一个模块 B 调用模块的 A 函数来读取位于模块 A 中的静态文件?

go - 如何从 Go 中的 nslookup 获取 "Name"?

go - 在Go中分离多个文件和包中的组件

戈朗 : Can you type a returned interface{} in one statement?