duansao20000508 2013-10-25 19:05
浏览 48
已采纳

在Go中编写更简洁的代码

I'm writing a package with functions which read data from XML-RPC server and store it in arrays of go structs. Here is the snippet just for two kinds of structs: http://play.golang.org/p/a1dVA0UCzS. For each type of struct I have a separate "conversion" function. There are more than 20 of them in total - just plain copies of each other with just struct names replaced.

Is there an elegant solution instead of stupid copy/paste of the same code?

  • 写回答

1条回答 默认 最新

  • dtgr6303 2013-10-26 01:36
    关注

    You can do this by using reflection. See the pkg/reflect documentation.

    For your case reflect.MakeFunc is interesting. You can create functions using reflection which then send a message and know the types they will receive. Example usage:

    var getFooRequest func() []Foo                      // Prototype of request.
    buildRequest("FooStore.GetFoo", &getFooRequest)     // Build request function.
    
    result := getFooRequest()                           // Actually sending.
    

    A working example (play):

    func makeRequestFunc(req string, fptr interface{}) {
        baseRequestFunc := func(params []reflect.Value) []reflect.Value {
            log.Println("Sending", req)
            return []reflect.Value{ reflect.ValueOf([]int{1,2,3,4}) }
        }
    
        fn := reflect.ValueOf(fptr).Elem()
        reqFun := reflect.MakeFunc(fn.Type(), baseRequestFunc)
        fn.Set(reqFun)
    }
    
    var fooRequest func() []int
    
    makeRequestFunc("foo", &fooRequest)
    
    log.Println( fooRequest() )
    

    baseRequestFunc in this example is the place where you would call your store.client.Call with whatever string you like. From this base function you create a new function that is callable using reflect.MakeFunc and store the result in the passed function pointer.

    As fooRequest has a definite signature, no value unpacking is needed.

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

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?