1

I am new to Go & I am trying to learn how to cast interface{} to a Map. Here is an example of what I am trying to implement.

Playground link : https://play.golang.org/p/3jhKlGKO46Z

Thanks for the help.

package main

import (
    "fmt"
)


func main() {

    Map := make(map[string]interface{})
    test(Map)

    for k,v := range Map {
        fmt.Println("key : %v Value : %v", k, v)
    }

}

func test(v interface{}) error{

    data := make(map[int]interface{})

    for i := 0; i < 10; i++ {
        data[i] = i * 5
    }

    for key,val := range data {
        //  fmt.Println("key : %v Value : %v", key, val)
        v[key] = val
    }

    return nil
5
  • 1
    Please take the Tour of Go, especially tour.golang.org/methods/15. And do not use the empty interface. Commented Apr 5, 2020 at 5:58
  • the test method is like a replica of a predefined method. so cannot change that Commented Apr 5, 2020 at 6:01
  • Go does not have a cast feature like other languages. The feature that you are looking for is called a type assertion. Use m := v.(Map) to assert that v is aMap. Commented Apr 5, 2020 at 6:21
  • One this I noticed is fmt.Println("key : %v Value : %v", k, v) here you need to use fmt.Printf. Commented Apr 5, 2020 at 6:28
  • stackoverflow.com/questions/47496040/… have a look, may helpful Commented Apr 5, 2020 at 6:33

1 Answer 1

4

Go supports type assertions for the interfaces. It provides the concrete value present in the interface.

You can achieve this with following code.

    m, ok := v.(map[int]interface{})
    if ok {
      // use m
      _ = m
    }

If the asserted value is not of given type, ok will be false

If you avoid second return value, the program will panic for wrong assertions.

I strongly recommend you to go through https://tour.golang.org

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.