Home > Back-end >  How can I use dynamic key for struct in Go lang?
How can I use dynamic key for struct in Go lang?

Time:03-26

I have this struct for get data from Json string.

    type msg struct {
         Msg1 string   `json:"msg1"`
         Msg2 string  `json:"msg2"`
         Msg3 string `json:"msg3"`
    }

And I need to use this struct like below.

num := // some random number under 3
data := msg.Msg   num  // as msg.Msg1, msg.Msg2...

How can I do this in Go lang?
I searched a lot but couldn't find any good solutions.

CodePudding user response:

How can I use dynamic key for struct in Go lang?

You simply cannot. This is not doable in Go.

(Use a map if you need this.)

CodePudding user response:

Just Show You How To Using Json And Map ,May be helpful

package main

import (
    "fmt"
    "encoding/json"
)
type sample struct{
    Member1 string `json:"TheMember1"`
}


func main() {
    map_contains := make(map[string]string)
    //Part 1 Direct Add to Map
    map_contains["w"]="mmmmm"
    fmt.Println(map_contains)
    fmt.Println(map_contains["w"])
    
    //Part 2 JsonString to Map
    json.Unmarshal([]byte(`{"a":"123"}`),&map_contains)
    fmt.Println(map_contains)
    fmt.Println(map_contains["a"])

    //Part 3 Struct To JsonString To Map
    s1:=sample{
        Member1:"June",
    }
    s1json,err:=json.Marshal(s1)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(s1json))
    json.Unmarshal(s1json,&map_contains)
    fmt.Println(map_contains)
    fmt.Println(map_contains["TheMember1"])
}
  •  Tags:  
  • go
  • Related