-3

Type assertion on a map doesn't work, is this the right way to do it?

Just to elaborate, my goal is to return a map with dynamic types. this example is just for demonstration.

package main

import "fmt"

func main()  {
    m := hello().(map[string]int)
    fmt.Println(m)
}

func hello() interface{} {
    return map[string]interface{} {
        "foo": 2,
        "bar": 3,
    }
}

it panics

panic: interface conversion: interface {} is map[string]interface {}, not map[string]int

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
f_i
  • 3,084
  • 28
  • 31
  • 1
    Whats the question? A `map[string]interface{}` isn't a `map[string]int` so the type assertion fails. – tkausl Sep 21 '19 at 08:30
  • am i right to suppose that the map has key as string and value as int? type assertion with types other then map works with those assumptions – f_i Sep 21 '19 at 08:34
  • You can't do a type assertion to an incompatible type. You must manually convert it instead. – Jonathan Hall Sep 21 '19 at 14:18

2 Answers2

0

return the appropriate type

package main

import "fmt"

func main()  {
    m := hello().(map[string]int)
    fmt.Println(m)
}

func hello() interface{} {
    return map[string]int{
        "foo": 2,
        "bar": 3,
    }
}
  • I am not at a liberty to return a static type, a map could hold any type as key and any type as value. right now for the sake of demonstration i have considered the values as interface. am i doing this right? – f_i Sep 21 '19 at 08:35
  • so you need map[interface{}]interface{} –  Sep 21 '19 at 08:37
  • yeah, if i can figure out map[string]interface{} for now i will see the second part later. – f_i Sep 21 '19 at 08:39
  • `Just to elaborate, my goal is to return a map with dynamic types` there is no such thing in go. You can however use interface{} to mixin multiple types. –  Sep 21 '19 at 08:41
  • i am using reflection to achieve that to some level. With other types it works but with maps i am getting this error. – f_i Sep 21 '19 at 08:43
-1

To answer my own question, assertion works on map values

a few examples

package main

import "fmt"

type person struct {
    name string
}

func main()  {
    m := example1().(map[string]interface{})

    fmt.Println(m["foo"].(int))

    m2 := example2().(map[string]interface{})

    fmt.Println(m2["foo"].(person).name)

}

func example1() interface{} {
    return map[string]interface{} {
        "foo": 2,
        "bar": 3,
    }
}

func example2() interface{} {
    m := make(map[string]interface{})

    m["foo"] = person{"Name is foo!"}
    m["bar"] = person{"Name is bar!"}

    return m
}
f_i
  • 3,084
  • 28
  • 31