Go type conversion method (conversion of interface type)

Time:2021-9-25

Go reports an error during type conversion:

cannot convert m (type interface {}) to type Msg: need type assertion

reason:

Go does not use type conversion in interface type conversion, but uses


t,ok := i.(T)

example:

//Processing network messages
func ProcessMsg(m interface{}){
    //var a interface{} = m
    //Msg(m)
    msg := m.(*Msg)

Supplement: type conversion of go [] interface {}

Look at the code~


package main 
import (
    "fmt"
    "strings"
)
 
func getName(params ...interface{}) string {
    var stringSlice []string
    for _, param := range params {
        stringSlice = append(stringSlice, param.(string))
    }   
    return strings.Join(stringSlice, "_")
}
 
func main() {
    fmt.Println(getName("redis", "slave", "master"))
}

If the above code types do not match, a panic error will be generated. If you want not to generate a panic error


str, ok := param.(string)

If ok is false, STR is empty and no error is reported.

You can also do this:


package main 
import (
    "fmt"
    "reflect"
    "strings"
)
 
func getName(params ...interface{}) string {
    var stringSlice []string
    for _, param := range params {
        stringSlice = append(stringSlice, param.(string))
    }   
    return strings.Join(stringSlice, "_")
}
 
func main() {
    var aa []interface{} = make([]interface{}, 3)
    aa[0] = "redis" 
    aa[1] = "slave" 
    aa[2] = "master" 
    fmt.Println(reflect.TypeOf(aa))
    fmt.Println(reflect.TypeOf(aa[0]))
    fmt.Println(getName(aa...))
}

Output:

[]interface {}

string

redis_slave_master

The above is my personal experience. I hope I can give you a reference, and I hope you can support developpaer. If you have any mistakes or don’t consider completely, please don’t hesitate to comment.