Variables
How
var a // 不定型別的變數
var a int // 宣告成 int
var a int = 10 // 初始化同時宣告
var a, b int // a 跟 b 都是 intvar a, b = 0, ""
var a int , b string
a := 0
a, b, c := 0, true, "tacolin" // 這樣就可以不同型別寫在同一行
var(
a bool = false // 記得要不同行,不然會錯
b int
c = "hello"
)
Where
Go is lexically scoped using blocks!
package main
import "fmt"
var x string = "Hello World"
func main() {
var y string = "Hello AAA"
fmt.Println(x) //Hello World
}
func aaa() {
fmt.Println(x) //Hello World
fmt.Println(y) //undefined: y
}
func bbb() {
fmt.Println(x) //Hello World
}
What
Go also has support for constants. Constants are basically variables whose values cannot be changed later.
const x string = "Owen is a good boy!"
x = "James is better." //cannot assign to x
var y string = "Disney kiss Ken"
y = "Louis kiss Ken" //it's okay!