0

I was looking for a way to convert a map to another map, without copying key by key. Both maps have the equivalent key type (as demonstrated below).

The code below seems to do the job, but I'm wondering what kind of pitfalls there might be if I use this?

package main

import (
 "fmt"
 "unsafe"
)

type A string
var (
  x A = "x"
  y A = "y"
)

func main() {
    a := map[A]string{}
    a[x] = "242342"
    a[y] = "1234"

    b := convert(a)

    fmt.Println(a[x])
    fmt.Println(b["x"])

    fmt.Println(a[y])
    fmt.Println(b["y"])
}

func convert(in map[A]string) map[string]string {
    return *(*map[string]string)(unsafe.Pointer(&in))
}
Kel
  • 1,217
  • 11
  • 21
  • 4
    A small note: it's not a type alias. Type alias is `type A = string`. And type aliases would work as-is. – zerkms Oct 31 '17 at 03:08
  • 3
    Pitfalls: the solution is not type safe and you must ensure `A` is a `string` on the caller side: https://play.golang.org/p/WkZp0CMKob – zerkms Oct 31 '17 at 03:11
  • 1
    I would try hard to avoid doing this; it's not guaranteed in any way to work in the future. Go does not have a polymorphic type system (by design). You must use interfaces to achieve any sort of polymorphism. – BadZen Oct 31 '17 at 19:34

0 Answers0