Solution Review: Advancing the Simple Interface
This lesson discusses the solution to the challenge given in the previous lesson.
We'll cover the following...
We'll cover the following...
Go (1.6.2)
package mainimport ("fmt")type Simpler interface { // interface declaring Simple methodsGet() intSet(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 intj 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 RSimpleswitch 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 Simplefmt.Println(fI(&s)) // &s is required because Get() is defined with the type pointer as receivervar r RSimplefmt.Println(fI(&r))}
As we stated in the discussion of the previous challenge, we can make other types that implement the interface Simpler
; the only condition is that they have at least one integer field. We illustrate this here by defining a type RSimple
(see implementation from line 23 ...