Skip to content

Commit

Permalink
Tweak interface example type assertion + update link
Browse files Browse the repository at this point in the history
  • Loading branch information
eliben committed Jan 6, 2025
1 parent 858d475 commit ad9cea3
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 36 deletions.
13 changes: 5 additions & 8 deletions examples/interfaces/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,12 @@ 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.
// Sometimes it's useful to know the runtime type of an
// interface value. One option is using a *type assertion*
// as shown here; another is a [type `switch`](switch).
func detectCircle(g geometry) {
if c, ok := g.(circle); ok {
fmt.Println(c.radius)
fmt.Println("circle with radius", c.radius)
}
}

Expand All @@ -71,9 +71,6 @@ func main() {
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(r)
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 @@
9a362e2c9aed98013fa9b91af81d6cc373979db6
tfsLP7R0dtH
6324a4bdb756a0ec2ccc60e13c97d2650e730ed6
xAAbgd7GOKD
6 changes: 3 additions & 3 deletions examples/interfaces/interfaces.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ $ go run interfaces.go
{5}
78.53981633974483
31.41592653589793
5
circle with radius 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).
# To understand how Go's interfaces work under the hood,
# check out this [blog post](https://research.swtch.com/interfaces).
35 changes: 12 additions & 23 deletions public/interfaces

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

0 comments on commit ad9cea3

Please sign in to comment.