Skip to content

Go 接口

定义与实现

go
type Writer interface {
    Write([]byte) (int, error)
}

// 隐式实现,不需要 implements 关键字
type FileWriter struct{}

func (w FileWriter) Write(data []byte) (int, error) {
    return len(data), nil
}

空接口

go
func printAny(v interface{}) {
    fmt.Println(v)
}

类型断言

go
var w Writer = FileWriter{}
if fw, ok := w.(FileWriter); ok {
    fmt.Println(fw)
}

常用接口

接口方法
io.ReaderRead(p []byte) (n int, err error)
io.WriterWrite(p []byte) (n int, err error)
fmt.StringerString() string
errorError() string

基于 VitePress 构建