Skip to content

Commit 858d475

Browse files
authored
added type assertion example (#567)
* added type assertion example * simplified example
1 parent 58894bd commit 858d475

File tree

4 files changed

+64
-8
lines changed

4 files changed

+64
-8
lines changed

examples/interfaces/interfaces.go

+15
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,15 @@ func measure(g geometry) {
5151
fmt.Println(g.perim())
5252
}
5353

54+
// Type assertion can be performed to explicitly check the runtime type of the value.
55+
// It allows the access of fields and methods belonging to the specific type.
56+
// See [`switch` example](switch) for an alternative approach to handle type assertion.
57+
func detectCircle(g geometry) {
58+
if c, ok := g.(circle); ok {
59+
fmt.Println(c.radius)
60+
}
61+
}
62+
5463
func main() {
5564
r := rect{width: 3, height: 4}
5665
c := circle{radius: 5}
@@ -61,4 +70,10 @@ func main() {
6170
// these structs as arguments to `measure`.
6271
measure(r)
6372
measure(c)
73+
74+
// `detectCircle` takes structs that satisfy the `geometry` interface
75+
// if the struct is of type `circle`, it prints out the radius.
76+
detectCircle(r) // doesn't print anything.
77+
detectCircle(c)
78+
6479
}

examples/interfaces/interfaces.hash

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
d4ea9541521cfee94107ba9331d0dabb1f9f16c1
2-
XJASG4MxBQr
1+
9a362e2c9aed98013fa9b91af81d6cc373979db6
2+
tfsLP7R0dtH

examples/interfaces/interfaces.sh

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ $ go run interfaces.go
55
{5}
66
78.53981633974483
77
31.41592653589793
8+
5
89

910
# To learn more about Go's interfaces, check out this
1011
# [great blog post](https://jordanorelli.tumblr.com/post/32665860244/how-to-use-interfaces-in-go).

public/interfaces

+46-6
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)