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

Structs และ Methods

TypeScript มี class, interface และ object ธรรมดา ส่วน Go มี structs — type ข้อมูลล้วนๆ — และ methods — ฟังก์ชันที่ผูกติดกับ type ไม่มี class ไม่มี inheritance ไม่มีคีย์เวิร์ด this (Go ใช้ receiver ที่ตั้งชื่อได้แทน)

TypeScript
// TypeScript interface + object
interface User {
name: string;
age: number;
}
const u: User = { name: "Alice", age: 30 };
console.log(u.name);
Go
// Go struct
type User struct {
Name string
Age int
}
u := User{Name: "Alice", Age: 30}
fmt.Println(u.Name)

ใน TypeScript method อยู่ภายใน class แต่ใน Go คุณผูก method เข้ากับ type ใดก็ได้ด้วยการระบุ receiver ไว้หน้าชื่อฟังก์ชัน

TypeScript
class User {
constructor(
public name: string,
public age: number,
) {}
greet(): string {
return `Hi, I'm ${this.name}`;
}
}
Go
type User struct {
Name string
Age int
}
// Method with value receiver
func (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 struct
func (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)
}
คีย์เวิร์ดใดที่ใช้นิยาม struct ใน Go?
ควรใช้ pointer receiver เมื่อ:
อะไรคือสิ่งเทียบเท่ากับ this ของ JavaScript ภายใน method ใน Go?
Go นำโค้ดกลับมาใช้ซ้ำได้อย่างไรโดยไม่มี inheritance?