ข้ามไปยังเนื้อหา

Go 101 — พื้นฐาน

โมดูลนี้ครอบคลุมองค์ประกอบพื้นฐานของ Go ในมุมมองของนักพัฒนา TypeScript แต่ละบทจะโยงแนวคิดของ Go เข้ากับสิ่งที่คุณรู้อยู่แล้ว แล้วค่อยแสดงวิธีแบบ Go

  • Variableslet/const:=, zero values เทียบกับ undefined
  • Functions — signature, การคืนค่าหลายค่า, named returns, variadics
  • Control Flowif, loop for หนึ่งเดียวที่ทำได้ทุกอย่าง, switch, range
  • Collections — arrays เทียบกับ slices, maps (เวอร์ชัน Go ของ object/Map ใน JS)
  • Structs & Methods — value types, receivers (คำตอบของ Go ต่อแนวคิด class)
  • Interfaces — การ satisfy แบบ implicit (เป็น structural แต่ก็ชัดเจน — คล้าย TS แต่ก็ต่างกัน)
  • Errors — error เป็น value ไม่ใช่ exception
  • Packages — Go modules, exported identifiers, imports

ใน TypeScript คุณคงเขียนแบบนี้อยู่ทุกวัน:

const greet = (name: string): string => {
return `Hello, ${name}!`;
};
console.log(greet("World"));

ใน Go แนวคิดเดียวกันจะหน้าตาแบบนี้:

package main
import "fmt"
func greet(name string) string {
return fmt.Sprintf("Hello, %s!", name)
}
func main() {
fmt.Println(greet("World"))
}

มีหลายอย่างที่สะดุดตาทันที: ต้องประกาศ package main อย่างชัดเจน, ไม่มี arrow function, ใช้ fmt สำหรับการแสดงผลแบบจัดรูปแบบ, และ type อยู่ หลัง ชื่อ parameter ทั้งหมดนี้จะรู้สึกเป็นธรรมชาติเมื่อคุณเรียนจบโมดูลนี้

ใน Go type จะปรากฏตรงไหนเมื่อเทียบกับชื่อ parameter?