Home > Software engineering >  how to convert lua table to golang map[string]string
how to convert lua table to golang map[string]string

Time:01-28

the following is lua table return value, it likes array:

[clientID abcde state 1 activity 8 deviceType 4 seq 1]

enter image description here

I want to covert to golang map[string]string like here:

{
"clientId": "abcde",
"state": "1",
"activity": "8",
"deviceType": "4",
"seq": "1"}

how to do ?

CodePudding user response:

That's one way I think(an example):

func convert() {
    var arr = []string{"k1", "v1", "k2", "v2", "k3", "v3", "k4", "v4", "k5", "v5", "k6", "v6"}
    var res = map[string]string{}
    for i := 0; i < len(arr)/2; i   {
        val := arr[i*2 : i*2 2]
        res[val[0]] = val[1]
    }
}

CodePudding user response:

This works fine

func convert(kvs []string) map[string]string{
    if len(kvs)%2 != 0 {
        panic("num of kvs item should be even")
    }

    result := make(map[string]string, len(kvs)/2)
    for i := 0; i < len(kvs)-1; i =2 {
        result[kvs[i]] = kvs[i 1]
    }
    return result
}

  •  Tags:  
  • Related