Trung BìnhGolang iconGolang

Interface trong Go hoạt động thế nào?

Interface = tập hợp method signatures.

Implicit implementation: struct tự động satisfy interface nếu có đủ methods (không cần implements keyword).

go
// Định nghĩa interface
type Writer interface {
    Write([]byte) (int, error)
}

type Stringer interface {
    String() string
}

// Struct tự động satisfy interface
type MyWriter struct{}

func (w MyWriter) Write(p []byte) (int, error) {
    fmt.Print(string(p))
    return len(p), nil
}

// Dùng interface làm tham số — polymorphism
func save(w Writer, data []byte) error {
    _, err := w.Write(data)
    return err
}

// Empty interface chấp nhận mọi type
func printAny(v any) {
    fmt.Println(v)
}

interface{} (hoặc any) là empty interface chấp nhận mọi type.

Xem toàn bộ Golang cùng filter theo level & chủ đề con.

Mở danh sách Golang