Add example of type assertions
Resources:
- https://go.dev/ref/spec#Type_assertions
- https://go.dev/tour/methods/15
This could be useful if a good example can be worked out. There's some related code in the switch and json examples already, but maybe this would go to interfaces
This could be useful if a good example can be worked out. There's some related code in the
switchandjsonexamples already, but maybe this would go tointerfaces
I recommend this to go into interfaces. The perimeter of a circle is also called a circumference so a circum() method could be defined on the circle struct that does the same as perim(). Do type assertion against a shape to check if it's circle or rect before calling either perim() or circum()
Example below
// alias for perim()
func(c circle) circum() float64 {
return c.perim()
}
shapeSlice := []geometry{rect{width: 5, length: 10}, circle{radius: 5}}
for _, shape := range shapeSlice {
fmt.Println(shape.area())
if r, ok := shape.(rect); ok {
fmt.Println(r.perim())
}
if c, ok := shape.(circle); ok {
fmt.Println(r.circum())
}
}
Edit: made a PR. The example in PR is simpler than above stated example
Could Go by Example have a separate example for Type Assertions, instead of including it as part of other examples? I’ve prepared a PR https://github.com/mmcgrana/gobyexample/pull/586 for discussion
This issue should have been closed when #567 landed. I think this is sufficiently demonstrated now, and a separate example isn't required