gobyexample icon indicating copy to clipboard operation
gobyexample copied to clipboard

Add example of type assertions

Open adriancuadrado opened this issue 1 year ago • 1 comments

Resources:

  • https://go.dev/ref/spec#Type_assertions
  • https://go.dev/tour/methods/15

adriancuadrado avatar Apr 16 '24 02:04 adriancuadrado

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

eliben avatar Apr 16 '24 12:04 eliben

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

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

kevin-kho avatar Jan 03 '25 20:01 kevin-kho

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

akalanitski avatar May 02 '25 14:05 akalanitski

This issue should have been closed when #567 landed. I think this is sufficiently demonstrated now, and a separate example isn't required

eliben avatar May 02 '25 18:05 eliben