Consider:
type Maker interface {
Name() string
Type() string
}
type BallMaker interface {
R() int
Circ() int
}
type SquareMaker interface {
Width() int
Perimeter() int
}
If I want to check what my Maker
is:
if maker.Type() == ''BallMaker" {
//make balls
}
Or
s, ok := maker.(SquareMaker)
if ok {
// make squares
}
Which one is idiomatic?
评论:
rdigel:
whizack:I would always choose the type assertion. For one, there's no risk of mistyping the magic string.
ui7_uy8:the short answer is that your question lacks sufficient context. neither are really idiomatic go because a problem like this would not be modeled as multiple interface types that don't satisfy the same interface.
taking a stab at an approximation of your problem, I'd consider doing something like this: https://play.golang.org/p/s9GPE3UId2N
The answer is "it depends", really, especially when the compiler will restrict when you can use the second one.
