douye9822 2014-07-10 11:33
浏览 14
已采纳

如何设置结构域抛出接口?

everyone!

My task is to parse command-line argument and fill struct fields. And my function must works with all kinds of arguments - they'll describe in struct tag.

For example:

type CommndLineArguments struct {
   Configfile string `required:"false" name:"config" default:"/etc/daemon.conf" description:"Config file"`
   Daemon     bool `required:"true" name:"daemon" default:"false" description:"Run as daemon"`
}

I use reflect and flag packages. Like this:

func    GetArguments(variable interface{}) error {
//Check is this a pointer to struct
variableType := reflect.TypeOf(variable)
if variableType.Kind() != reflect.Ptr {
    return errors.New(ERR_PASS_BY_VALUE)
} else if variableValue := variableType.Elem(); variableValue.Kind() != reflect.Struct {
    return errors.New(ERR_NOT_A_STRUCT)
}

// Parse parameters

variableValue := variableType.Elem()

for i := 0; i < variableValue.NumField(); i++ {
    structField := variableValue.Field(i)
    fieldName := structField.Name
    fieldType := structField.Type
    fieldTag := structField.Tag

Now I'm ready to parse arguments.

switch fieldType.Kind() {
    case reflect.Bool:
        defaultValue, err := strconv.ParseBool(fieldTag.Get("default"))
        if err != nil {
            return errors.New(ERR_PARSE_ERROR + err.Error())
        }
        flag.BoolVar(&structField, fieldName, defaultValue, fieldTag.Get("description"))

But I get an error in last line.

./parser.go:42: cannot use &structField (type *reflect.StructField) as type *bool in function argument

My question is how can I set this field correctly?

  • 写回答

1条回答 默认 最新

  • dourui7186 2014-07-10 14:30
    关注

    You will have to get the address of the field (also use ValueOf not TypeOf):

    flag.BoolVar(fld.Addr().Interface().(*bool), fieldName, defaultValue, fieldTag.Get("description"))
    

    Simple demo @ http://play.golang.org/p/yEG-OH6d4W

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染