Dan
Dan

Reputation: 51

How to populate struct from file

I have a struct that is designed like this:

type UrlData struct {
    As int 
    Iso string 
}

I instantiate it and after that I read a text file (see below) so as to check if certain struct field is equal to a value from the txt file (yes, I know that it would be much easier to compare explicitly, but reading the data from file is the requirement to be met)

The txt file has the following format:

as 646
iso us

When reading the txt file, I want to know if the *UrlData.As field (in the instantiated item) is equal to the value from file, i.e. 646.

The problem is I don't know how to match current field from the txt file with the name of the struct field. What is the most adequate way to do that?

Upvotes: 0

Views: 427

Answers (1)

Cosmic Ossifrage
Cosmic Ossifrage

Reputation: 5379

You will need to implement a mechanism which can determine which field is named on the line and match this against the corresponding field in the structure. The field identification is easy: use strings.Split on a line read from the file, split on the space, and retrieve the first value.

Looking this up in the struct can take a couple of approaches. The simplest would explicitly test this in a conditional or similar (I have avoided showing code to read the file, as the crux of your question seems to be the matching with the struct values):

// Struct
var myStruct *UrlData = // some instantiation

// Read line from file
line = // TODO

// Determine the field
parts := strings.Split(line, " ")
name, value := parts[0], parts[1]

// Look up the fields in the struct
switch name {
case "as":
        return myStruct.As == value
case "iso":
        return myStruct.Iso == value
}

It is also possible to use reflection to dynamically look up the struct field from the name in the file, but this will be more complex and should be avoided until you require a truly generic solution (and even then best avoided - reflection is not clear code!).

Upvotes: 2

Related Questions