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 1 commit
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
14 changes: 14 additions & 0 deletions examples/interfaces/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ func (c circle) perim() float64 {
return 2 * math.Pi * c.radius
}

// `circle` has a method called `circum` not part of `geometry` interface.
// `circum` is an alias for `perim`
func (c circle) circum() float64 {
return c.perim()
}

// If a variable has an interface type, then we can call
// methods that are in the named interface. Here's a
// generic `measure` function taking advantage of this
Expand All @@ -61,4 +67,12 @@ func main() {
// these structs as arguments to `measure`.
measure(r)
measure(c)

// Type assertion can be performed
// to access methods not part of the `geometry` interface
var shape geometry
shape = circle{radius: 6}
if c, ok := shape.(circle); ok {
fmt.Println(c.circum())
}
}
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
f536687ba84047d88affba161c521d72b3759627
iRa1sADCdAw
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
37.69911184307752

# 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).
41 changes: 36 additions & 5 deletions public/interfaces

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