How to determine an interface{} value's "real" type?

Viewed 143953

I have not found a good resource for using interface{} types. For example

package main

import "fmt"

func weirdFunc(i int) interface{} {
    if i == 0 {
        return "zero"
    }
    return i
}
func main() {
    var i = 5
    var w = weirdFunc(5)

    // this example works!
    if tmp, ok := w.(int); ok {
        i += tmp
    }

    fmt.Println("i =", i)
}

Do you know of a good introduction to using Go's interface{}?

specific questions:

  • how do I get the "real" Type of w?
  • is there any way to get the string representation of a type?
  • is there any way to use the string representation of a type to convert a value?
8 Answers

There are multiple ways to get a string representation of a type. Switches can also be used with user types:

var user interface{}
user = User{name: "Eugene"}

// .(type) can only be used inside a switch
switch v := user.(type) {
case int:
    // Built-in types are possible (int, float64, string, etc.)
    fmt.Printf("Integer: %v", v)
case User:
    // User defined types work as well  
    fmt.Printf("It's a user: %s\n", user.(User).name)
}

// You can use reflection to get *reflect.rtype
userType := reflect.TypeOf(user)
fmt.Printf("%+v\n", userType)

// You can also use %T to get a string value
fmt.Printf("%T", user)

// You can even get it into a string
userTypeAsString := fmt.Sprintf("%T", user)

if userTypeAsString == "main.User" {
    fmt.Printf("\nIt's definitely a user")
}

Link to a playground: https://play.golang.org/p/VDeNDUd9uK6

You can use

  1. Printf("%T", interface{})
  2. reflect.TypeOf
  3. reflect.ValueOf(x).Kind()

-> reflect:

 func typeofobject(x interface{}){
        fmt.Println(reflect.TypeOf(x))
 }

-> Printf()

 // Golang program to find the variable type
    package main
    
    // importing required packages
    import (
      "fmt"
    )
    
    // main function
    func main() {
      f := true
      st := ""
      a := 1
      d := 1.0
      arr := []string{"Go", "Is", "Fun"}
    
      fmt.Printf("%T\n", f)
      fmt.Printf("%T\n", st)
      fmt.Printf("%T\n", a)
      fmt.Printf("%T\n", d)
      fmt.Printf("%T\n", arr)
    }

OUTPUT:

bool
string
int
float64
[]string

-> reflect.ValueOf(x).Kind())

func typeofobject(x interface{}){
    fmt.Println(reflect.ValueOf(x).Kind())
}

source: geeks-for-geeks

Related