Go语言中的接口组合

huangapple go评论75阅读模式
英文:

Composition of interfaces in Go

问题

有没有办法在Go语言中使一个接口包含另一个接口定义的方法?

例如:

type BasicDatabase interface {
    CreateTable(string) error
    DeleteTable(string) error
}

type SpecificDatabase interface {
    BasicDatabase
    CreateUserRecord(User) error
}

我想要一种方式来指定SpecificDatabase接口包含BasicDatabase接口。类似于Go语言允许你对结构体进行组合的方式。

这样,我的方法可以接受实现了SpecificDatabase接口的类型,并在其上调用CreateTable()方法。

英文:

Is there a way to make an interface also include the methods defined by another interface in Go?

For example:

type BasicDatabase interface {
    CreateTable(string) error
    DeleteTable(string) error
}

type SpecificDatabase interface {
    CreateUserRecord(User) error
}

I would like a way to specify that the SpecificDatabase interface contains the BasicDatabase interface. Similar to the way Go lets you do composition of structs.

This way my methods can take a type that implements SpecificDatabase, but still call CreateTable() on it.

答案1

得分: 26

这可以通过与组合结构体时相同的方式来完成。

type BasicDatabase interface {
    CreateTable(string) error
    DeleteTable(string) error
}

type SpecificDatabase interface {
    BasicDatabase
    CreateUserRecord(User) error
}
英文:

This can be done the same way as when composing structs.

type BasicDatabase interface {
    CreateTable(string) error
    DeleteTable(string) error
}

type SpecificDatabase interface {
    BasicDatabase
    CreateUserRecord(User) error
}

huangapple
  • 本文由 发表于 2015年5月11日 08:21:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/30158023.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定