Skip to content

Commit

Permalink
simplified example
Browse files Browse the repository at this point in the history
  • Loading branch information
kevin-kho committed Jan 4, 2025
1 parent 17359b7 commit 6d59536
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 39 deletions.
27 changes: 14 additions & 13 deletions examples/interfaces/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,6 @@ 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 @@ -57,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 @@ -68,11 +71,9 @@ func main() {
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())
}
// `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 @@
f536687ba84047d88affba161c521d72b3759627
iRa1sADCdAw
9a362e2c9aed98013fa9b91af81d6cc373979db6
tfsLP7R0dtH
2 changes: 1 addition & 1 deletion 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
37.69911184307752
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).
55 changes: 32 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 6d59536

Please sign in to comment.