Search⌘ K
AI Features

Solution Review: Advancing the Simple Interface

Explore how to advance simple interfaces in Go by implementing new types with integer fields and using type switches to differentiate and handle these types effectively. Understand the practical use of pointers with struct types in interfaces to modify and access values dynamically. This lesson prepares you for deeper interface implementation concepts in Go.

We'll cover the following...
Go (1.6.2)
package main
import (
"fmt"
)
type Simpler interface { // interface declaring Simple methods
Get() int
Set(int)
}
type Simple struct {
i int
}
func (p *Simple) Get() int {
return p.i
}
func (p *Simple) Set(u int) {
p.i = u
}
type RSimple struct {
i int
j int
}
func (p *RSimple) Get() int {
return p.j
}
func (p *RSimple) Set(u int) {
p.j = u
}
func fI(it Simpler) int { // switch cases to judge whether it's Simple or RSimple
switch it.(type) {
case *Simple:
it.Set(5)
return it.Get()
case *RSimple:
it.Set(50)
return it.Get()
default:
return 99
}
return 0
}
func main() {
var s Simple
fmt.Println(fI(&s)) // &s is required because Get() is defined with the type pointer as receiver
var r RSimple
fmt.Println(fI(&r))
}

As we ...