doucheng3811 2018-02-26 15:21
浏览 215
已采纳

如何使用reflect.Type执行类型断言

I know reflection is generally frowned upon in go but for my current purposes Im pretty sure it is the best solution.

Essentially my project is cli tool which will output an xml query based on incoming commands and return the corresponding result.

There is some boiler plate code for each command request where default values are populated and supplied values validated.

So I have a series of Command objects based on a Command struct as follows:

type Command struct {
    Name        string
    Request     interface{}
    RequestType reflect.Type
    Response    interface{}

    RegisterFunc func(parentCmd *cobra.Command, cmd *Command) error
}

For the most part I really don't care about the types of the request/response (just xml encode/decode). However I need to briefly cast it to a concrete type to validate with struct annotations So for example I might do something like this:

    var ccReq *CreateCredentialRequest
    var set bool
    if ccReq, set = command.Request.(*CreateCredentialRequest); !set {
        log.Fatal(errors.New("invalid request type"))
    }

    result, err := govalidator.ValidateStruct(ccReq)
    if err != nil {
        println("error: " + err.Error())
        os.Exit(1)
    }

However in an ideal would I would like to handle this generically for all commands, something like this:

    var ccReq *CreateCredentialRequest
    var set bool
    if ccReq, set = command.Request.(command.RequestType); !set {
        log.Fatal(errors.New("invalid request type"))
    }

However this results in the error:

command.RequestType is not a type

So, how can I store the value of a type for a later type assertion

Note: Following discussion in comments with JimB it seems that i do not actually need the concrete type for validation purposes (interface is fine) but I still need further down to assert the response type to provide a custom response handler

  • 写回答

1条回答 默认 最新

  • doujiao2000 2018-02-26 15:30
    关注

    From the reflect.Type docs:

    Type values are comparable, such as with the == operator, so they can be used as map keys. Two Type values are equal if they represent identical types.

    If you want to compare underlying types, compare the reflect.Type values directly:

    if reflect.TypeOf(command.Request) != command.RequestType {
        log.Fatal(errors.New("invalid request type"))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥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美术毛发渲染