convert interface{} to certain type

Fast/Best way is 'Cast' in time execution (if you know the object):

E.g.

package main    
import "fmt"    
func main() {
    var inter (interface{})
    inter = "hello"
    var value string
    value = inter.(string)
    fmt.Println(value)
}

Try here


objx package makes exactly what you want, it can work directly with JSON, and will give you default values and other cool features:

Objx provides the objx.Map type, which is a map[string]interface{} that exposes a powerful Get method (among others) that allows you to easily and quickly get access to data within the map, without having to worry too much about type assertions, missing data, default values etc.

This is a small example of the usage:

o := objx.New(m1) 
s := o.Get("m1").Str() 
x := o.Get("x").Int() 
y := o.Get("y").Bool()

arr := objx.New(m1["a"])

A example from doc working with JSON:

// use MustFromJSON to make an objx.Map from some JSON
m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`)

// get the details
name := m.Get("name").Str()
age := m.Get("age").Int()

// get their nickname (or use their name if they
// don't have one)
nickname := m.Get("nickname").Str(name)

Obviously you can use something like this with the plain runtime:

switch record[field].(type) {
case int:
    value = record[field].(int)
case float64:
    value = record[field].(float64)
case string:
    value = record[field].(string)
}

But if you check objx accessors you can see a complex code similar to this but with many case of usages, so i think that the best solution is use objx library.


I came here trying to convert from interface{} to bool and Reflect gave me a clean way to do it:

Having:

v := interface{}
v = true

The solution 1:

if value, ok := v.(bool); ok {
  //you can use variable `value`
}

The solution 2:

reflect.ValueOf(v).Bool()

Then reflect offers a function for the Type you need.

Tags:

Casting

Go