Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang dynamic access to a struct property

Tags:

struct

go

I am writing a quick ssh config to json processor in golang. I have the following stuct:

type SshConfig struct {
    Host string
    Port string
    User string
    LocalForward string
    ...
}

I am currently looping over every line of my ssh config file and splitting the line on spaces and checking which property to update.

if split[0] == "Port" {
    sshConfig.Port = strings.Join(split[1:], " ")
}

Is there a way to check a property exists and then set it dynamically?

like image 547
Charles Bryant Avatar asked Dec 24 '17 14:12

Charles Bryant


People also ask

How do you access a struct variable in go?

Go by Example: Structs This person struct type has name and age fields. newPerson constructs a new person struct with the given name. You can safely return a pointer to local variable as a local variable will survive the scope of the function. This syntax creates a new struct.

How do you assign a value to a struct in Golang?

Default values can be assigned to a struct by using a constructor function. Rather than creating a structure directly, we can use a constructor to assign custom default values to all or some of its members.

How do you use struct in Go?

To work with a struct, you need to create an instance of it. The var keyword initializes a variable and, using dot notation, values are assigned to the struct fields. You must now create a struct type Player. Here, you have assigned the values to the struct while creating an instance ply1.


1 Answers

Use the reflect package to set a field by name:

// setField sets field of v with given name to given value.
func setField(v interface{}, name string, value string) error {
    // v must be a pointer to a struct
    rv := reflect.ValueOf(v)
    if rv.Kind() != reflect.Ptr || rv.Elem().Kind() != reflect.Struct {
        return errors.New("v must be pointer to struct")
    }

    // Dereference pointer
    rv = rv.Elem()

    // Lookup field by name
    fv := rv.FieldByName(name)
    if !fv.IsValid() {
        return fmt.Errorf("not a field name: %s", name)
    }

    // Field must be exported
    if !fv.CanSet() {
        return fmt.Errorf("cannot set field %s", name)
    }

    // We expect a string field
    if fv.Kind() != reflect.String {
        return fmt.Errorf("%s is not a string field", name)
    }

    // Set the value
    fv.SetString(value)
    return nil
}

Call it like this:

var config SshConfig

...

err := setField(&config, split[0], strings.Join(split[1:], " "))
if err != nil {
   // handle error
}

playground example

like image 65
Bayta Darell Avatar answered Oct 13 '22 07:10

Bayta Darell