ในการศึกษา Golang ตอนที่ 4 นั้นเน้นเรื่องพื้นฐานประกอบไปด้วย
การประกาศค่าคงที่
การประกาศตัวแปร และกำหนดค่าเริ่มต้น
แต่เมื่อลงไปศึกษาจริงๆ พบว่าใน Go มันมีความสามารถที่เยอะจริงๆ
Constant
ประกาศค่าคงที่ด้วย constant expression ชื่อว่า const
จะทำงานในขณะ compile
ชนิดข้อมูลที่สามารถประกาศเป็นค่าคงที่ได้ ประกอบไปด้วย
- boolean
- rune หรือ character
- integer
- floating-point
- string
ตัวอย่างการประกาศค่าคงที่
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)
เมื่อเห็นตัวอย่างการใช้งาน constant จากเอกสาร Effective Go
เจอ iota ซึ่งมันคืออะไร
เมื่อลงไปดูใน Specification ของ Go ในส่วน Iota
พบว่าเมื่อมันถูกใช้ใน constant expression แล้ว
จะกำหนดค่าเริ่มต้นเป็น 0 เสมอ
เมื่อเรียกซ้ำใน constant expression เดียวกัน มันจะเพิ่มขึ้นมา 1
เพื่อความไม่งง ดังตัวอย่าง
const ( a0 = iota a1 = iota a2 = iota ) const ( b0 = iota b1 = iota b2 = iota ) func main(){ fmt.Println(a0) fmt.Println(a1) fmt.Println(a2) fmt.Println(b0) fmt.Println(b1) fmt.Println(b2) }
ผลการทำงานเป็นดังนี้
0
1
2
0
1
2
กลับมาที่ code ตัวอย่างเจอแบบนี้ ถึงกับงงกันไปเลย
const ( _ = iota KB ByteSize = 1 << (10 * iota) MB GB TB PB EB ZB YB )
เมื่อดูในรายละเอียดแล้วพบว่า
จะทำการข้ามหรือไม่สนใจค่าจาก iota ตัวแรกคือ 0
ดังนั้นเมื่อเรียก iota อีกรอบจะได้ค่าเป็น 1
แล้วถ้าในบรรทัดต่อมาหรือเรียกว่า ExpressionList มีชนิดเดียวกันแล้ว
ค่าของ iota จะเพิ่มให้เองในแต่ละค่าคงที่
จึงทำให้ถึงบางอ้อ สำหรับกรณีนี้
Variable
การประกาศตัวแปรนั้นด้วย variable expression ชื่อว่า var
โดยสามารถกำหนดค่าเริ่มต้นได้ในลักษณะเดียวกับค่าคงที่
แต่ว่าจะทำงานในขณะ runtime
ตัวอย่างการประกาศตัวแปร
var ( home = os.Getenv("HOME") user = os.Getenv("USER") gopath = os.Getenv("GOPATH") )
Reference Website
http://golang.org/doc/effective_go.html#initialization
http://blog.golang.org/strings
http://golang.org/ref/spec#Rune_literals
http://golang.org/ref/spec#Constant_expressions
http://golang.org/ref/spec#Iota