Structs และ Methods
คำตอบของ Go ต่อแนวคิด class
หัวข้อที่มีชื่อว่า “คำตอบของ Go ต่อแนวคิด class”TypeScript มี class, interface และ object ธรรมดา ส่วน Go มี structs — type ข้อมูลล้วนๆ — และ methods — ฟังก์ชันที่ผูกติดกับ type ไม่มี class ไม่มี inheritance ไม่มีคีย์เวิร์ด this (Go ใช้ receiver ที่ตั้งชื่อได้แทน)
การนิยาม struct
หัวข้อที่มีชื่อว่า “การนิยาม struct”// TypeScript interface + objectinterface User { name: string; age: number;}
const u: User = { name: "Alice", age: 30 };console.log(u.name);// Go structtype User struct { Name string Age int}
u := User{Name: "Alice", Age: 30}fmt.Println(u.Name)Methods บน struct
หัวข้อที่มีชื่อว่า “Methods บน struct”ใน TypeScript method อยู่ภายใน class แต่ใน Go คุณผูก method เข้ากับ type ใดก็ได้ด้วยการระบุ receiver ไว้หน้าชื่อฟังก์ชัน
class User { constructor( public name: string, public age: number, ) {}
greet(): string { return `Hi, I'm ${this.name}`; }}type User struct { Name string Age int}
// Method with value receiverfunc (u User) Greet() string { return "Hi, I'm " + u.Name}ลองเล่นดู
หัวข้อที่มีชื่อว่า “ลองเล่นดู”package main
import "fmt"
type Rectangle struct { Width float64 Height float64}
func (r Rectangle) Area() float64 { return r.Width * r.Height}
func (r Rectangle) Perimeter() float64 { return 2 * (r.Width + r.Height)}
// Pointer receiver — can mutate the structfunc (r *Rectangle) Scale(factor float64) { r.Width *= factor r.Height *= factor}
func main() { rect := Rectangle{Width: 4, Height: 3} fmt.Printf("Area: %.1f\n", rect.Area()) fmt.Printf("Perimeter: %.1f\n", rect.Perimeter())
rect.Scale(2) fmt.Printf("After scaling: %.1f x %.1f\n", rect.Width, rect.Height)}Loading Go runtime (first run only, ~8 MB)…