Variables, Types และ Zero Values
ตัวแปรใน TypeScript เทียบกับ Go
หัวข้อที่มีชื่อว่า “ตัวแปรใน TypeScript เทียบกับ Go”ใน TypeScript คุณมี let สำหรับตัวแปรที่เปลี่ยนค่าได้, const สำหรับ binding แบบ immutable และ type inference ผ่าน : คุณยังคุ้นกับค่าที่เป็น undefined ก่อนถูกกำหนดค่าด้วย
Go มีกลไกที่คล้ายกันแต่มีกฎที่สะอาดกว่า และมีแนวคิดหนึ่งที่ TypeScript ไม่มีคำตอบโดยตรง นั่นคือ zero values
การประกาศตัวแปร
หัวข้อที่มีชื่อว่า “การประกาศตัวแปร”Go มีสองรูปแบบ การประกาศแบบสั้น := (ใช้ได้เฉพาะภายในฟังก์ชัน) จะ infer type จากฝั่งขวามือ — เหมือนกับ let x = ใน TypeScript ส่วนรูปแบบยาว var ใช้ในระดับ package หรือเมื่อคุณต้องการประกาศโดยยังไม่กำหนดค่าทันที
// TypeScriptlet count: number = 0;let name = "Alice"; // inferred as stringconst MAX = 100;// Govar count int = 0name := "Alice" // inferred as stringconst MAX = 100Type inference ด้วย :=
หัวข้อที่มีชื่อว่า “Type inference ด้วย :=”โอเปอเรเตอร์ := คือตัวหลักของ Go สำหรับตัวแปรในระดับ local ทั้งประกาศและกำหนดค่าในขั้นตอนเดียว — ไม่ต้องมี let ไม่ต้องระบุ type annotation เมื่อ type ชัดเจนอยู่แล้ว
let score = 42; // numberlet ratio = 3.14; // numberlet label = "hello"; // stringlet active = true; // booleanscore := 42 // intratio := 3.14 // float64label := "hello" // stringactive := true // boolConstants
หัวข้อที่มีชื่อว่า “Constants”ค่าคงที่ใน Go ทำงานเหมือน const ใน TypeScript — เป็น immutable และประเมินค่าตอน compile time นอกจากนี้ Go ยังมี iota สำหรับสร้างลำดับแบบ enum ที่เพิ่มค่าอัตโนมัติ (จะกล่าวถึงภายหลัง)
const PI = 3.14159;const APP_NAME = "MyApp";const PI = 3.14159const AppName = "MyApp"ลองเล่นดู
หัวข้อที่มีชื่อว่า “ลองเล่นดู”package main
import "fmt"
func main() { // Short declaration name := "Gopher" age := 3
// Long form (package-level style) var score int = 100
const greeting = "Hello"
fmt.Printf("%s, %s! Age: %d, Score: %d\n", greeting, name, age, score)}Loading Go runtime (first run only, ~8 MB)…