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 (
type User struct{
    Name string
func main() {
    any := User{
        Name: "fidding",
    any2 := "fidding"
    any3 := int32(123)
    any4 := int64(123)
    any5 := []int{1, 2, 3, 4, 5}
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)
        // Convert interface to slice type
        op := make([]int, 0) //[]
        op = value.([]int)

Leave a Reply

Your email address will not be published. Required fields are marked *