miekg / learninggo

Learning Go Book in mmark
https://miek.nl/go
Other
547 stars 107 forks source link

Remove invalid switch cases for interface example #18

Closed mamachanko closed 8 years ago

mamachanko commented 8 years ago

Thanks for the great book, @miekg!

Is it possible that there's a little issue with the example on switching by p.(type) here? Following the example leads to code that's not compiling:

package main

import "fmt"

type S struct{ i int }

func (s *S) Get() int  { return s.i }
func (s *S) Put(n int) { s.i = n }

type R struct{ i int }

func (s *R) Get() int  { return s.i }
func (s *R) Put(n int) { s.i = n }

type I interface {
    Get() int
    Put(int)
}

func f(p I) {
    switch p.(type) {
    case *S:
        fmt.Println("It's an *S")
    case *R:
        fmt.Println("It's an *R")
    }
}

func main() {
    s := S{}
    f(&s)
}

Running it yields errors:

$ go run main.go
# command-line-arguments
./main.go:26: impossible type switch case: p (type I) cannot have dynamic type S (missing Get method)
./main.go:28: impossible type switch case: p (type I) cannot have dynamic type R (missing Get method)

I am just starting to learn the ropes. But I think the issue is that both case S and case R aren't possible, because Put(int) requires a pointer rather than the value. Please, check my fix.

miekg commented 8 years ago

looks legit, thanks!