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

added type assertion example #567

Merged
merged 2 commits into from
Jan 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.

Loading