如何惯用地检查接口是否是Go中的两种类型之一



假设我有一个函数接受一个非常广泛的接口,它可以包装(?(或描述许多不同的类型,如int64float64string以及其他接口。然而,这个特定的函数只想与浮点和int进行交互,并且会为任何其他底层的具体类型返回一个错误。

围棋中惯用的方法是什么?

intfloat64的情况下,我是否应该使用switch语句而不执行任何操作,并在默认情况下返回错误?这对我来说似乎很奇怪,因为那些箱子本来就是空的。

例如

type BoardInterface interface{
doThing()
}
type customInt int
type customFloat float64
func (i customInt) doThing() {}
func (f customFloat) doThing() {}
// Other methods for different types here...
func getThing(i BoardInterface) error {
// i could be string, int, float, customInterface1, customInterface2...
// but we want to assert that it is int or float.
switch t := i.(type) {
case customInt:
// Do nothing here?
case customFloat:
// Do nothing here?
default:
return fmt.Errorf("Got %v want float or int", t)
}
// Do something with i here now that we know
// it is a float or int.
i.doThing()
return nil
}

理想情况下,BoardInterface应该包含您想要使用i的所有行为,这样您就可以"交互";通过CCD_ 9中列出的方法与CCD_。这样,i中包裹的混凝土类型应该无关紧要。如果编译器允许传递一个值,则必须保证它实现BoardInterface

如果由于某种原因,这是不可行的(或不可能的(,你提出的解决方案是好的。您可以通过在一个简单的case中列出所有允许的类型来简化它,而无需声明t,您可以像这样使用i

switch i.(type) {
case customInt, customFloat:
default:
return fmt.Errorf("Got %T want customInt or customFloat", i)
}

(注意,我在错误消息中使用了%T,因为在这种情况下信息更丰富。(

最新更新