全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-14 5 分钟 ✍️ juanwangdev

Go接口定义与实现

Go接口是方法签名的集合,类型只需实现所有方法即可满足接口。

接口定义

定义语法

Go
// 定义接口
type Reader interface {
    Read(p []byte) (n int, err error)
}

// 多方法接口
type Writer interface {
    Write(p []byte) (n int, err error)
}

// 组合接口
type ReadWriter interface {
    Reader  // 嵌入Reader接口
    Writer  // 嵌入Writer接口
}

方法签名格式

Go
type Handler interface {
    Handle(ctx context.Context, data string) error
}

// 方法签名 = 方法名 + 参数 + 返回值
// 不包含接收者

接口实现

隐式实现

Go
type Reader interface {
    Read(p []byte) (int, error)
}

// 只需实现方法,无需声明implements
type MyReader struct{}

func (m MyReader) Read(p []byte) (int, error) {
    return len(p), nil
}

// MyReader自动满足Reader接口
var r Reader = MyReader{}

Go接口隐式实现,类型实现方法即可满足接口。

实现所有方法

Go
type ReadWriter interface {
    Read(p []byte) (int, error)
    Write(p []byte) (int, error)
}

// 必须实现所有方法
type MyRW struct{}

func (m MyRW) Read(p []byte) (int, error) {
    return len(p), nil
}

func (m MyRW) Write(p []byte) (int, error) {
    return len(p), nil
}

var rw ReadWriter = MyRW{}

接口变量

接口赋值

Go
type Printer interface {
    Print()
}

type Console struct{}

func (c Console) Print() {
    fmt.Println("Console打印")
}

// 值赋值
var p Printer = Console{}

// 指针赋值
var p Printer = &Console{}

接口调用方法

Go
var p Printer = Console{}
p.Print()  // 调用Console.Print()

// 接口变量存储:
// 类型信息 + 数据指针

接口类型检查

编译时检查

Go
// 确保类型实现接口
var _ Reader = MyReader{}  // 编译时验证

// 如果MyReader不满足Reader,编译错误

接口满足条件

Go
// 条件1:方法签名完全一致
func (m MyReader) Read(p []byte) (int, error)

// 条件2:实现所有接口方法
type Reader interface {
    Read(p []byte) (int, error)  // 必须实现
}

// 条件3:方法名和参数类型一致
// Read vs read:方法名必须一致

接口使用示例

Go
// 定义接口
type Shape interface {
    Area() float64
    Perimeter() float64
}

// 实现类型
type Rectangle struct {
    Width, Height float64
}

func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

func (r Rectangle) Perimeter() float64 {
    return 2 * (r.Width + r.Height)
}

type Circle struct {
    Radius float64
}

func (c Circle) Area() float64 {
    return 3.14 * c.Radius * c.Radius
}

func (c Circle) Perimeter() float64 {
    return 2 * 3.14 * c.Radius
}

// 多态使用
func printShape(s Shape) {
    fmt.Println("面积:", s.Area())
    fmt.Println("周长:", s.Perimeter())
}

printShape(Rectangle{3, 4})
printShape(Circle{5})

接口定义规则

规则说明
方法签名方法名 + 参数 + 返回值
实现方式类型实现所有方法
隐式满足无需声明implements
类型检查编译时验证
方法签名一致名称、参数、返回值完全匹配

要点总结

  • interface定义方法签名集合
  • 类型实现所有方法即满足接口
  • Go接口隐式实现,无需声明
  • 接口变量存储类型信息和数据指针
  • 编译时用var _ Interface = Type{}检查
  • 方法签名必须完全一致
  • 值和指针类型都可赋给接口
  • 接口实现多态,统一调用方式

📝 发现内容有误?点击此处直接编辑

← 上一篇 Go接口与多态
下一篇 → Go接口嵌套
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库