我有以下类型:
type Statement interface {
Say() string
}
type Quote struct {
quote string
}
func (p Quote) Say() string {
return p.quote
}
func Replay(conversation []Statement) {
for _, statement := range conversation {
fmt.Println(statement.Say())
}
}
我认为我很好地理解了为什么函数接受类型参数[]Statement
,不能用[]Quote
;虽然Quote
实施Statement
, []Quote
不实施[]Statement
. []Statement
甚至不是一个接口。它有类型slice of Statement
。虽然 Go 隐式从类型转换为接口类型,但它不会从类型切片进行隐式转换A
到界面的一部分B
.
我们可以显式地将引号转换为语句:
conversation := []Quote{
Quote{"Nice Guy Eddie: C'mon, throw in a buck!"},
Quote{"Mr. Pink: Uh-uh, I don't tip."},
Quote{"Nice Guy Eddie: You don't tip?"},
Quote{"Mr. Pink: Nah, I don't believe in it."},
Quote{"Nice Guy Eddie: You don't believe in tipping?"},
}
// This doesn't work
// Replay(conversation)
// Create statements from quotes
statements := make([]Statement, len(conversation))
for i, quote := range conversation {
statements[i] = quote
}
Replay(statements)
现在假设 Replay 是一个库的一部分,该库希望不遗余力地提高 Replay 使用的简单性。它允许您使用任何对象片段调用 Replay,只要这些对象实现了 Statement 接口。为此,它具有以下转换方法:
func ConvertToStatements(its interface{}) ([]Statement, error) {
itsValue := reflect.ValueOf(its)
itsKind := itsValue.Kind()
if itsKind != reflect.Array && itsKind != reflect.Slice {
return nil, fmt.Errorf("Expected items to be an Array or a Slice, got %s", itsKind)
}
itsLength := itsValue.Len()
items := make([]Statement, itsLength)
for i := 0; i < itsLength; i++ {
itsItem := itsValue.Index(i)
if item, ok := itsItem.Interface().(Statement); ok {
items[i] = item
} else {
return nil, fmt.Errorf("item #%d does not implement the Statement interface: %s", i, itsItem)
}
}
return items, nil
}
重播看起来像这样:
func Replay(its interface{}) {
conversation := ConvertToStatements(its)
for _, statement := range conversation {
fmt.Println(statement.Say())
}
}
我们现在可以直接用引号调用 Replay:
Replay(conversation)
最后,我的问题是:是否有更简单的方法可以让 Replay 接受任意类型 A 的切片,只要 A 实现了 Statement 接口?