Go 避免返回接口的设计模式
我的应用程序有以下我特意简化的模型,我认为在我使用接口的方式中有很多代码味道:Go 避免返回接口的设计模式,go,design-patterns,Go,Design Patterns,我的应用程序有以下我特意简化的模型,我认为在我使用接口的方式中有很多代码味道: type Library interface { ListCollections(prefix string) []Collection GetItemLocation(item Item) string } type Collection interface { SearchItems(query string) []Item } type Item interface {
type Library interface {
ListCollections(prefix string) []Collection
GetItemLocation(item Item) string
}
type Collection interface {
SearchItems(query string) []Item
}
type Item interface {
Name() string
Summary() string
}
type Library interface {
ListCollections(prefix string) []Collection
GetItemLocation(item Item) string
}
type Collection interface {
SearchItems(query string) []Item
}
type Item interface {
Name() string
Summary() string
}
我无法定义项
结构,因为每个结构都不同。然而,对于外部世界,拥有项
接口就足够了
如您所见,我有返回接口的方法,但我并不喜欢它。此外,在本例中,我很难处理GetItemLocation
部分:它需要一个项,但我需要访问该项的字段(特定于每个集合),因此它强制我在方法内键入cast参数
我可以使用哪些模式来分解这种复杂性并编写更多的diomatic go代码?必须在
GetItemLocation()
中使用类型断言对我来说似乎不是一个阻碍。也可以考虑不要期望<代码>项目>代码>而只是项目的ID(或者用于标识它的任何东西)。断言的唯一问题是将应该编译时类型的安全性转换为运行时错误。