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 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'