Golang新手可能会踩的50个坑-02未使用的变量

in cn •  6 years ago 

如果在函数提代码中有未使用的变量,则无法通过编译,不过全局变量声明但不使用是可以的。
即使变量声明后为变量赋值,依旧无法通过编译,需在某处使用它:

package main

// 错误实例
var gvar int  // 全局变量,声明不使用也可以

func main() {
    var one int
    two := 2
    var three int
    three = 3
}

/*
# command-line-arguments
./test.go:7:6: one declared and not used
./test.go:8:2: two declared and not used
./test.go:9:6: three declared and not used
*/
package main

// 正确实例
// 可以直接注释或移除未使用的变量

func main() {
    var one int
    _ = one

    two := 2
    println(two)

    var three int
    one = three

    var four int
    four = four
}
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!