Golang动态访问struct属性 [英] Golang dynamic access to a struct property
本文介绍了Golang动态访问struct属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用golang将快速ssh配置写入json处理器.我有以下结构:
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
...
}
我目前正在遍历ssh配置文件的每一行,并将行拆分为空格并检查要更新的属性.
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?
推荐答案
使用 reflect 包设置字段按名称:
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
}
这样称呼:
var config SshConfig
...
err := setField(&config, split[0], strings.Join(split[1:], " "))
if err != nil {
// handle error
}
这篇关于Golang动态访问struct属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文