

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 4
click for more info
Not enough gems
Cost: 6 gems
1: Interfaces in Go
incomplete
2: Interface Implementation
incomplete
3: Interfaces Are Implemented Implicitly
incomplete
4: Interfaces Quiz
incomplete
5: Multiple Interfaces
incomplete
6: Name Your Interface Parameters
incomplete
7: Type Assertions in Go
incomplete
8: Type Switches
incomplete
9: Clean Interfaces
incomplete
10: Message Formatter
incomplete
11: Process Notifications
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
When working with interfaces in Go, every once-in-awhile you'll need access to the underlying type of an interface value. You can cast an interface to its underlying type using a type assertion.
The example below shows how to safely access the radius field of s when it is not known that s is a circle:
type shape interface {
area() float64
}
type circle struct {
radius float64
}
func (c circle) area() float64 {
// ...
}
func printShapeInfo(s shape) {
c, ok := s.(circle)
if ok {
radius := c.radius
fmt.Printf("s is a circle, radius: %v\n", radius)
return
}
}
In printShapeInfo:
s is a circle in order to cast it into its underlying concrete types is an instance of the shape interface, but we do not know if it's also a circlec is a new circle struct cast from sok is true if s is indeed a circle, or false if s is NOT a circleImplement the getExpenseReport function.