Cannot type switch on non-interface value

雨燕双飞 提交于 2019-12-20 17:26:08

问题


I am playing with type assertion using the following dummy code, and I got the error:

cannot type switch on non-interface value

Does anyone know what does that mean?

package main

import "fmt"
import "strconv"

type Stringer interface {
    String() string
}

type Number struct {
    v int
}

func (number *Number) String() string {
    return strconv.Itoa(number.v)
}

func main() {
    n := &Number{1}
    switch v := n.(type) {
    case Stringer:
        fmt.Println("Stringer:", v)
    default:
        fmt.Println("Unknown")
    }
}

http://play.golang.org/p/Ti4FG0m1mc


回答1:


Type switches require an interface to introspect. If you are passing a value of known type to it it bombs out. If you make a function that accepts an interface as a parameter, it will work:

func typeSwitch(tst interface{}) {
    switch v := tst.(type) {
        case Stringer:
           fmt.Println("Stringer:", v)
        default:
           fmt.Println("Unknown")
    }
}

See the full code here http://play.golang.org/p/QNyf0eG71_ and the golang documentation on interfaces http://golang.org/doc/effective_go.html#interfaces.




回答2:


I figured out the answer, which is to cast n to interface{} before the type assertion:

switch v := interface{}(n).(type)



回答3:


There are two kinds of type conversions

  1. conversion between basic data types. For this we can use the direct casting

    i := 48

    str := string(i)

  2. But type conversion using value.(type) is for conversion among the class hierarchy, (e.g. where we want to get the specific implementation from the interface). Else, we get the above error.




回答4:


There are no typecasts in Go. You are doing a type conversion.



来源:https://stackoverflow.com/questions/23172219/cannot-type-switch-on-non-interface-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!