Jonathon Reinhart
Jonathon Reinhart

Reputation: 137438

Map lookup via anonymous struct key

I have the following map whose key type is an anonymous struct:

var data map[struct{ pID, bID int }]string

Question: How would I go about constructing a key to actually get/set a value in data?

I've tried these, which all result in compiler errors:

data[{1,2}] = "ok"
data[{pID: 1, bID 2}] = "ok"

It seems I cannot form a compound literal without having the type name, but there is no type name.


This related question uses an anymous struct as the value of a map, but not the key:

Upvotes: 2

Views: 736

Answers (1)

Yandry Pozo
Yandry Pozo

Reputation: 5123

You can create anonymous keys as well, something like this:

func main() {

    data := map[struct{ pID, bID int }]string{}

    key := struct{pID, bID int}{1, 2}
    data[key] = "abc"

    data[struct{pID, bID int}{3, 4}] = "cha cha cha"


    fmt.Printf("%+v\n\n", data)

    fmt.Printf("'%s' '%s'\n", data[key], data[struct{pID, bID int}{3, 4}])
}

Full file: https://play.golang.org/p/2q11qiwxuI

Upvotes: 3

Related Questions