# 基本變數宣告

``````var x int = 10
``````

``````var x, y, z int = 10, 20, 30
``````

``````var (
x int = 10
y string = "Justin"
z bool = true
)
``````

``````var (
a bool
b int32
c float32
d string
e complex128
)
``````

# 自動推斷型態

``````var x = 10
``````

``````var x, y, z = 10, 3.14, "Justin"
``````

`x``y``z` 的型態分別會是 `int``float64``string`，批量宣告時也可以自動推斷型態，例如：

``````var (
x = 10        // int 型態
y = 3.14      // float32 型態
z = "Justin"  // string 型態
)
``````

# 短變數宣告

``````x := 10
y := 3.14
z := "Justin"
``````

``````x, y, z := 10, 3.14, "Justin"
``````

`var` 宣告的變數名稱不可重複，然而，短變數宣告時，若同一行內有新宣告了另一變數，就可以重複宣告已存在的變數，例如，以下是合法的，因為使用 `:=` 時有一個新的 `y` 變數：

``````var x = 10
x, y :=  20, 30
``````

``````package main

import "fmt"

func main() {
var x = true
if x {
fmt.Println(x)
}
}
``````

``````package main

import "fmt"

func main() {
if x := true; x {
fmt.Println(x)
}
}
``````

（在數學上 `A := B` 的寫法，涵義是藉由 B 來定義 A，例如數學上若已經定義 `x` 以及 `f(x)``x := f(x)` 表示用舊的 `x` 定義新的 `x`，這反而像是程式語言中的 `x = f(x)` 指定的概念，當然，數學上的符號與程式語言中的符號是有出入的，Go 在這邊只是借用了 `:=` 來作為另一種變數宣告符號。）

# 調換變數值

``````var x = 10
var y = 20
x, y = y, x
``````

# 基本常數宣告

``````const x = 10
``````

``````const x int32 = 10
``````

``````const (
x = 10
y = 3.14
z = "Justin"
)
``````

``````const (
x int = 10
y float32 = 3.14
z string = "Justin"
)
``````

``````package main

import "fmt"

func main() {
const (
x = 10
y = 3.14
z = "Justin"
)

fmt.Println(x)
fmt.Println(y)
}
``````

# 常數運算式

``````const a = 2 + 3.0          // a == 5.0   (untyped floating-point constant)
const b = 15 / 4           // b == 3     (untyped integer constant)
const c = 15 / 4.0         // c == 3.75  (untyped floating-point constant)
const Θ float64 = 3/2      // Θ == 1.0   (type float64, 3/2 is integer division)
const Π float64 = 3/2.     // Π == 1.5   (type float64, 3/2. is float division)
const d = 1 << 3.0         // d == 8     (untyped integer constant)
const e = 1.0 << 3         // e == 8     (untyped integer constant)
const f = int32(1) << 33   // illegal    (constant 8589934592 overflows int32)
const g = float64(2) >> 1  // illegal    (float64(2) is a typed floating-point constant)
const h = "foo" > "bar"    // h == true  (untyped boolean constant)
const j = true             // j == true  (untyped boolean constant)
const k = 'w' + 1          // k == 'x'   (untyped rune constant)
const l = "hi"             // l == "hi"  (untyped string constant)
const m = string(k)        // m == "x"   (type string)
const Σ = 1 - 0.707i       //            (untyped complex constant)
const Δ = Σ + 2.0e-4       //            (untyped complex constant)
const Φ = iota*1i - 1/1i   //            (untyped complex constant)
``````

# 使用 iota 列舉

``````const (
x = iota   // 0
y = iota   // 1
z = iota   // 2
)
``````

``````const (
x = 1
y      // 1
z      // 1
)
``````

``````const (
x = iota   // 0
y          // 1
z          // 2
)
``````

``````const x, y, z = iota, iota, iota
``````