tengo icon indicating copy to clipboard operation
tengo copied to clipboard

Use variable as key name when building a map literal

Open novuscy opened this issue 4 years ago • 2 comments

Hello, I have a script like this:

k := "someKey"
v := "someValue"
data := {
  k: v 
}

fmt.println(data)

the output is {k: "someValue"}, but the result I wish for is {someKey: "someValue"}, Is there a syntax that I can make a map literal with variable as key name? just like in JavaScript:

const data = {
  [k]: v 
}

Thanks.

novuscy avatar Aug 14 '20 08:08 novuscy

You can do this:

k := "someKey"
v := "someValue"
data := {}
data[k] = v

fmt := import("fmt")
fmt.println(data)

geseq avatar Aug 17 '20 07:08 geseq

You can do this:

k := "someKey"
v := "someValue"
data := {}
data[k] = v

fmt := import("fmt")
fmt.println(data)

Thanks for your reply.

Yeah, that is the way I used, but it's not very convenient for some deeply nested object, I wonder if there's a more convenient way to achieve that?

novuscy avatar Aug 17 '20 09:08 novuscy