20

Go语言变量定义,每省略一次声明,就会刨一个坑

 3 years ago
source link: https://studygolang.com/articles/30664
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在Go语言中,变量可以声明之后再赋值,也可以不声明,直接就用。

var strM string
strM = "Hello Golang"

strN := "Hello Golang"

我刚开始的时候有点困惑,一把锁为什么要配两把钥匙,使用一种方法不就香吗?

知道刚才,我碰到一个问题,才发现Golang定义这两种方式,真的很香。

package main

import "fmt"

func main() {
    n := map[string]int{
        "n1":1,
        "n2":2,
    }
    
    if k, ok := n["n2"];ok{
        fmt.Println(k," is there")
        fmt.Println(ok)
    }else{
        fmt.Print(k," is NOT there")
    }
    
    fmt.Println(ok)
}

程序运行的结果会出错。

# command-line-arguments
./main.go:18:14: undefined: ok

在if那里,不是已经定义了变量ok吗,为什么后面打印的时候会报错呢?

这是因为在go语言里,有一种范围叫做语义(context),这个变量是在if语句里直接赋值使用的,没有实现声明,它的作用域仅仅局限在if这个语义之下,超出if语句就不起作用了。

现在我把它先声明一下。

package main

import "fmt"

func main() {
    n := map[string]int{
        "n1":1,
        "n2":2,
    }
    
    var ok bool //ok is declared
    var k int
    
    if k, ok = n["n2"];ok{
        fmt.Println(k," is there")
        fmt.Println(ok)
    }else{
        fmt.Print(k," is NOT there")
    }
    
    fmt.Println(ok)
}

运行的结果是:

2  is there
true
true

这是我初次在简书里面写代码块,看到别人的文章里,代码块都是带行号的,折腾了半天我也弄不出来,谁能告诉我一下,应该需要怎么做?

有疑问加站长微信联系

iiUfA3j.png!mobile

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK