-4

I have a function that excepts parameter of type map[string]interface{} but I have variable of type map[string][]byte. my question is how can I convert map[string][]byte to map[string]interface{} in Go.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Revital Eres
  • 233
  • 5
  • 18
  • 8
    With a loop: create a new `map[string]interface{}`, iterate over a map you have and fill it. – zerkms Feb 23 '21 at 21:50
  • Does this answer your question? [Converting slice of structs to slice of empty interface](https://stackoverflow.com/questions/9121515/converting-slice-of-structs-to-slice-of-empty-interface) –  Jul 23 '21 at 11:44

3 Answers3

0

This is a common miss-expectation from go. In this case each element of the map needs to be converted to interface. So here's a workaround with sample code:

func foo(arg map[string]interface{}){
    fmt.Println(arg)
}

// msaToMsi convert map string array of byte to map string interface
func msaToMsi(msa map[string][]byte) map[string]interface{}{
    msi := make(map[string]interface{}, len(msa))
   for k, v := range msa {
       msi[k] = v
    }
    return msi
}

func main() {
    msa := map[string][]byte{"a": []byte("xyz")}
    foo(msaToMsi(msa))
}

The solution would be similar for the following map or array conversion as well: map[string]string to map[string]interface{} []string to [] interface {} Etc..

Kanak Singhal
  • 3,074
  • 1
  • 19
  • 17
0

Ok so to answer your question an interface in GO can be used where you are passing or receiving a object/struct of where you are not sure of its type.

For example:

type Human struct {
    Name string
    Age int
    School string
    DOB time.Time
}

type Animal struct {
    Name string
    HasTail bool
    IsMamal bool
    DOB time.Time
}

func DisplayData(dataType interface{}, data byte) 

This Display Data function can Display any type of data, it takes data and a struct both of which the function doesn't know until we pass them in... The data could be a Human or an Animal, both having different values which can be mapped depending on which interface we pass to the function...

This means we can reuse the code to display any data as long as we tell the function the data type we want to map the data to and display (i.e. Animal or Human...)

In your case the solution would be to define the data type, the structure of the data in the byte as a struct and where you make the map instead of map[string][]byte try changing to map[string]YourDefinedStructure

and pass that to the function that accepts map[string]interface{}.

Hopefully this helps, the question although you supply data types is rather vague as a use case and nature of the function that accepts map[string]interface{} can affect the approach taken.

Ollie Beumkes
  • 301
  • 2
  • 17
-1

You don't really have to convert while passing your map[string][]byte to the function. The conversion needs to happen at the point where you want to use the value from the map.

Alok
  • 5
  • 4