Home > Software engineering >  GoLang parsing string to struct
GoLang parsing string to struct

Time:12-06

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

The first thing that comes to mind is to split the line for example by "] " and then go through all the slices, breaking each element "[" and read out the data. Is there some way to do this more correctly?

CodePudding user response:

  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.

CodePudding user response:

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.

  • Related