Struct และ Interface

Go Interfaces

Describe behavior as a list of methods. Any type that has them satisfies the interface automatically.

  • ระดับกลาง
  • อ่าน 4 นาที
  • ตัวอย่างที่รันได้ 1 ตัวอย่าง
สิ่งที่คุณจะได้เรียนรู้
  • Defining an interface
  • Implicit implementation
  • any and type assertions
interface Shape
  • ShapeArea(), Name()
    • Circle
    • Rect

Behavior, not inheritance

An interface lists methods. Any type that has those methods satisfies the interface automatically: there is no implements keyword. Code written against the interface works with every such type.

Circle and Rect both have Area and Name, so both can be stored in a []Shape and passed to describe. any is the interface with no methods, which every value satisfies. value.(Circle) is a type assertion: ok is true when the value really is a Circle.

ประเด็นสำคัญ

  1. There is no implements keyword.
  2. A []Shape can hold different types.
  3. value.(Circle) checks the real type.

ตัวอย่าง Go ที่รันได้

Go
รันโค้ด →
main.go
package main

import (
	"fmt"
	"math"
)

type Shape interface {
	Area() float64
	Name() string
}

type Circle struct{ Radius float64 }
type Rect struct{ Width, Height float64 }

func (c Circle) Area() float64 { return math.Pi * c.Radius * c.Radius }
func (c Circle) Name() string  { return "circle" }
func (r Rect) Area() float64   { return r.Width * r.Height }
func (r Rect) Name() string    { return "rectangle" }

func describe(shape Shape) {
	fmt.Printf("%s: %.2f\n", shape.Name(), shape.Area())
}

func main() {
	shapes := []Shape{Circle{Radius: 1}, Rect{Width: 2, Height: 3.5}}
	for _, shape := range shapes {
		describe(shape)
	}

	var value any = shapes[0]
	if circle, ok := value.(Circle); ok {
		fmt.Println("radius:", circle.Radius)
	}
}
สร้างปุ่ม Run สำหรับตัวอย่างนี้ ผลลัพธ์จากการรันโค้ด
circle: 3.14
rectangle: 7.00
radius: 1

ฝึกฝน

เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์

เรียนบทนี้จบแล้วใช่ไหม

ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า

ถัดไป: Struct Embedding and Composition →

ฝึกด้วยโจทย์

ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI

โจทย์ทั้งหมด