2

I have a map of type set, which is actually a map[string]string. However, passing it to a function which accepts a map[string]string fails, because Go does not recognize set as one.

However, I fail to convince the compiler it is one. Is there any way to resolve this, without looping and copying?

package main

import (
    "fmt"
)

type name string
type field string

type set map[name]field      // map[string]string after all
type plain map[string]string // also map[string]string

func main() {
    var typed = set{"hi": "ho"} // map[string]string?

    back := plain(typed)  // cannot convert typed (type set) to type plain
    back := typed.(plain) // invalid type assertion: typed.(plain) (non-interface type set on left)

    echo(back)
}

func echo(in map[string]string) {
    fmt.Println(in)
}
7
  • 2
    Those types aren't equivalent. You can't convert between map[name]field and map[string]string. Commented Jun 7, 2019 at 14:02
  • 2
    Both error messages clearly state the problem. In Go defining a type like your field is only sensible if you need to attach methods or this type is a major, standalone one. In your code you will have to copy the map. Commented Jun 7, 2019 at 14:09
  • 2
    No, you need to loop and copy. Commented Jun 7, 2019 at 14:10
  • 1
    Loop and copy it is. If you think this is wasteful: Don't use different types set and plain. Dead simple. Commented Jun 7, 2019 at 14:19
  • 3
    Yes, I dislike the different types as well. But this is being done here github.com/prometheus/common/blob/… so I need to deal with it. Commented Jun 7, 2019 at 14:21

1 Answer 1

2

You could do this using the unsafe package.

Note: I don't think this would necessarily be a good idea, and probably the right way would be to just iterate and copy, but since it does answer the question asked...

var typed = set{"hi": "ho"} // map[string]string?
p := unsafe.Pointer(&typed)
var back plain
back = *(*plain)(p)

Playground: https://play.golang.org/p/yienSuJSnQU

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

1 Comment

Okay, wow! I didn't think of unsafe. While this is probably a bad way to use, it answers the original question. Thanks! Nevertheless, loop and copy seems to be the way to go.

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.