-2

How do I convert a string to a structure?

The line looks like this: Name[data1] Name2[data1 data2 data3] Name3[data1 data2] ...

The data can be of type Int, String, or Float. In general, this is not important, you can write everything as string.

Data in brackets is separated by a space

What I got using regexp:

func Parse() {
    str := "Version[2f0] Terminal[10002] Machine[10.1.1.1] DH[0.137%] Temp[45] Fan[0] Vo[4074 4042 4058 4098] CRC[0 0 0 0]"
    j := make(map[string][]string)

    re, err := regexp.Compile(`(?P<Name>[^ \[]*)\[(?P<Value>[^\]]*)`)
    if err != nil {
        log.Fatal(err)
    }
    res := re.FindAllSubmatch([]byte(str), -1)
    for _, match := range res {
        j[string(match[1])] = strings.Split(string(match[2]), " ")
    }

    log.Printf("%+v", j)
}

Could there be a more elegant way using json.Unmarshal?

Oleg E
  • 11
  • 1
  • 2
    read any basic guide to go for example here is the section on structs from "a tour of go" https://go.dev/tour/moretypes/1 – Vorsprung Dec 05 '21 at 15:28

2 Answers2

1

If you're free to use any tool you like, a regular expression might make this fairly easy.

(?P<Name>\[^\[\]*)\[(?P<Values>\[^\]\]*)\]

That matches each of the named value sets.

and then you could split the Values group at the spaces with string.Split

To create a dynamic struct you'd need to use reflection. Avoid reflection, though, as you learn Go. A struct in Go is unlike an object in say Javascript or Python, where fields are dynamic at runtime. Go structs are meant to have static fields.

For this purpose, a map[string][]string would be a more appropriate type. The key would be the Name fields, and the value would be the data fields.

erik258
  • 14,701
  • 2
  • 25
  • 31
1
  1. You need to define a specific format for the serializing the data. A key part of that will be how to encode specific special characters, such as the [ and ]. You generally do not want to do this.
  2. If you want to use any string as a temporary textual representation of your data and the format doesn't matter, you can just use JSON and use json.Marshal() and json.Unmarshal().

I'm not sure what you are trying to achieve (what's this struct data? what generated it? why are you trying to decode it into a struct?) but it seems that going through the fundamentals might be helpful:

I'm sure you can google the more in-depth articles when you identify what you need to know for your specific purposes.

Ivaylo Novakov
  • 775
  • 6
  • 18