Golang converts interface to int, string, slice, struct and other types

In golang, interface{} allows to accept arbitrary values, int, string, struct, slice, etc., so I can easily pass values to interface{}

However, when we pass any type into the test function and convert it to an interface, we often need to perform a series of operations that the interface does not have (that is, the incoming User structure, and the interface itself does not have the so-called Name attribute), then we need to Use the interface feature type assertions and type switches to convert it back to the original incoming type

package main
import (
    "fmt"
)
type User struct{
    Name string
}
func main() {
    any := User{
        Name: "fidding",
    }
    test(any)
    any2 := "fidding"
    test(any2)
    any3 := int32(123)
    test(any3)
    any4 := int64(123)
    test(any4)
    any5 := []int{1, 2, 3, 4, 5}
    test(any5)
}
func test(value interface{}) {
    switch value.(type) {
    case string:
        // Convert interface to string string type
        op, ok := value.(string)
        fmt.Println(op, ok)
    case int32:
        // Convert interface to int32 type
        op, ok := value.(int32)
        fmt.Println(op, ok)
    case int64:
        // Convert interface to int64 type
        op, ok := value.(int64)
        fmt.Println(op, ok)
    case User:
        // Convert interface to User struct type and use its Name object
        op, ok := value.(User)
        fmt.Println(op.Name, ok)
    case[]int:
        // Convert interface to slice type
        op := make([]int, 0) //[]
        op = value.([]int)
        fmt.Println(op)
    default:
        fmt.Println("unknown")
    }
}

Leave a Reply

Your email address will not be published.

en_USEnglish