Struct และ Interface
Go Methods: Value and Pointer Receivers
Go has no classes. Attach methods to a type and choose the right receiver.
สิ่งที่คุณจะได้เรียนรู้
- Methods and receivers
- Value vs pointer receiver
- Constructor functions
Receiver → what the method can do
func (r Rectangle) Area()read a copyfunc (r *Rectangle) Scale(f)change the originalA function with a receiver
A method is a function with a receiver: the value it is called on, written before the method name. Go has no classes, so methods on structs are how types get behavior.
Area has a value receiver and works on a copy, which is fine for reading. Scale has a pointer receiver, so it changes the original rectangle. Go takes the address for you when you call rect.Scale(2). NewSquare is an ordinary function used as a constructor.
ประเด็นสำคัญ
- A value receiver works on a copy.
- A pointer receiver can change the original.
- NewSquare is a normal function used as a constructor.
ตัวอย่าง Go ที่รันได้
main.go
package main
import "fmt"
type Rectangle struct {
Width, Height float64
}
func NewSquare(size float64) Rectangle {
return Rectangle{Width: size, Height: size}
}
// Area has a value receiver: it only reads the rectangle.
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
// Scale has a pointer receiver: it changes the rectangle.
func (r *Rectangle) Scale(factor float64) {
r.Width *= factor
r.Height *= factor
}
func main() {
rect := Rectangle{Width: 3, Height: 4}
fmt.Println("area:", rect.Area())
rect.Scale(2)
fmt.Println("scaled:", rect.Width, "x", rect.Height, "=", rect.Area())
fmt.Println("square:", NewSquare(5).Area())
}
area: 12
scaled: 6 x 8 = 48
square: 25ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- กฎของบัญชีธนาคาร ปกป้องยอดเงินในบัญชีด้วยกฎการฝากและถอน โดยปฏิเสธรายการที่ไม่ถูกต้อง ง่าย
- Distance Between Points Compute the straight-line distance between two points. ง่าย