The Type Switch
In this lesson, you'll learn how to use the switch statement to determine the type of interface and writing cases accordingly.
Testing the type of interface #
The type of an interface variable can also be tested with a special kind of switch: the type-switch. Look at the following program:
Press + to interact
Go (1.6.2)
package mainimport ("fmt""math")type Square struct {side float32}type Circle struct {radius float32}type Shaper interface {Area() float32}func main() {var areaIntf Shapersq1 := new(Square)sq1.side = 5areaIntf = sq1switch t := areaIntf.(type) {case *Square:fmt.Printf("Type Square %T with value %v\n", t, t)case *Circle:fmt.Printf("Type Circle %T with value %v\n", t, t)default:fmt.Printf("Unexpected type %T", t)}}func (sq *Square) Area() float32 {return sq.side * sq.side}func (ci *Circle) Area() float32 {return ci.radius * ci.radius * math.Pi}
The variable t
receives both value and type from areaIntf
. All of the listed ...