要点
- var用来定义一个变量
- 可以用:=这种shorter的方式,此时不用var
- const定义常量
- var/const (…)用来定义一组变量或常量
- 作用域同C/C++/Java等语法
变量声明&赋值
package main
import "fmt" // Printf()
/*
D:\examples>go run helloworld.go
Hello, world!
y - Hello world!
z - Hello world!
string a
string b
Hello, world! 1234567
y - Hello world! 1234567
D:\examples>
*/
func main() {
// <<Introducing Go>> Page 19:
// May look strange to experienced Go programmers.
var x string = "Hello, world!"
var y string
y = "y - Hello world!"
z := "z - Hello world!"
var ( // Attention Pls: Here is not '{'!
a = "string a"
b = "string b"
)
fmt.Println(x)
fmt.Println(y)
fmt.Println(z)
fmt.Println(a)
fmt.Println(b)
x = x + " 1234567"
fmt.Println(x)
y += " 1234567"
fmt.Println(y)
//a = 2 //cannot use 2 (type int) as type string in assignment
}
变量名
以字母开头,后面可以跟字母、数字、下划线。建议用camelCase风格。
作用范围
package main
import "fmt" // Printf()
var global_x = "Hello, world!"
func main() {
var x string = "Hello, world!"
fmt.Println(global_x)
fmt.Println(x)
foo();
}
func foo() {
fmt.Println("foo():", global_x)
//fmt.Println("foo():", x) //undefined: x
}
再一例:
package main
import "fmt"
var x int
func print(x int) {
fmt.Println("x = ", x)
}
/*
$ go run main.go
x = 100
x = 200
x = 101
$
*/
func main() {
foo()
print(x)
x++ // x = 101
bar()
print(x)
}
func foo() {
x = 100 // global variable 'x'
}
func bar() {
x := 200 // local variable 'x'
print(x)
}
常量
package main
import "fmt" // Printf()
func main() {
const x string = "Hello, world!"
//x = "Another value" // cannot assign to x
fmt.Println(x)
}
有疑问加站长微信联系(非本文作者)