Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example of type assertions #523

Open
adriancuadrado opened this issue Apr 16, 2024 · 2 comments
Open

Add example of type assertions #523

adriancuadrado opened this issue Apr 16, 2024 · 2 comments

Comments

@adriancuadrado
Copy link
Contributor

Resources:

@eliben
Copy link
Collaborator

eliben commented Apr 16, 2024

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

@kevin-kho
Copy link
Contributor

kevin-kho commented Jan 3, 2025

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants