doushi1510 2017-12-24 14:05
浏览 950
已采纳

Golang动态访问struct属性

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?

  • 写回答

3条回答 默认 最新

  • douganbi7686 2017-12-24 15:18
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里