Go 101 — พื้นฐาน
สิ่งที่คุณจะได้เรียนรู้
หัวข้อที่มีชื่อว่า “สิ่งที่คุณจะได้เรียนรู้”โมดูลนี้ครอบคลุมองค์ประกอบพื้นฐานของ Go ในมุมมองของนักพัฒนา TypeScript แต่ละบทจะโยงแนวคิดของ Go เข้ากับสิ่งที่คุณรู้อยู่แล้ว แล้วค่อยแสดงวิธีแบบ Go
- Variables —
let/const→:=, zero values เทียบกับundefined - Functions — signature, การคืนค่าหลายค่า, named returns, variadics
- Control Flow —
if, loopforหนึ่งเดียวที่ทำได้ทุกอย่าง,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 ทั้งหมดนี้จะรู้สึกเป็นธรรมชาติเมื่อคุณเรียนจบโมดูลนี้