Skip to content

Commit

Permalink
added type assertion example (#567)
Browse files Browse the repository at this point in the history
* added type assertion example

* simplified example
  • Loading branch information
kevin-kho authored Jan 6, 2025
1 parent 58894bd commit 858d475
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 8 deletions.
15 changes: 15 additions & 0 deletions examples/interfaces/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,15 @@ func measure(g geometry) {
fmt.Println(g.perim())
}

// Type assertion can be performed to explicitly check the runtime type of the value.
// It allows the access of fields and methods belonging to the specific type.
// See [`switch` example](switch) for an alternative approach to handle type assertion.
func detectCircle(g geometry) {
if c, ok := g.(circle); ok {
fmt.Println(c.radius)
}
}

func main() {
r := rect{width: 3, height: 4}
c := circle{radius: 5}
Expand All @@ -61,4 +70,10 @@ func main() {
// these structs as arguments to `measure`.
measure(r)
measure(c)

// `detectCircle` takes structs that satisfy the `geometry` interface
// if the struct is of type `circle`, it prints out the radius.
detectCircle(r) // doesn't print anything.
detectCircle(c)

}
4 changes: 2 additions & 2 deletions examples/interfaces/interfaces.hash
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
d4ea9541521cfee94107ba9331d0dabb1f9f16c1
XJASG4MxBQr
9a362e2c9aed98013fa9b91af81d6cc373979db6
tfsLP7R0dtH
1 change: 1 addition & 0 deletions examples/interfaces/interfaces.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ $ go run interfaces.go
{5}
78.53981633974483
31.41592653589793
5

# To learn more about Go's interfaces, check out this
# [great blog post](https://jordanorelli.tumblr.com/post/32665860244/how-to-use-interfaces-in-go).
52 changes: 46 additions & 6 deletions public/interfaces

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 858d475

Please sign in to comment.