Skip to content

Commit

Permalink
added type assertion example
Browse files Browse the repository at this point in the history
  • Loading branch information
kevin-kho committed Jan 3, 2025
1 parent 58894bd commit 17359b7
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 7 deletions.
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.

0 comments on commit 17359b7

Please sign in to comment.