doushen8391 2014-12-11 09:00
浏览 28
已采纳

在Go中传递任何类型的惯用方式(同时保持编译时的类型检查?)

I am parsing a form and have written a number of functions func parseAndValidateX(val string) (T, err) where T is any type.

Now I would like to write a closure func catchError(T, Error) T, so that I can do something like:

errors []Error

func catchError(val T, err Error) T {
    if err != nil {
        //append err to errors
    }
    return val
}


data = MyStruct {
Age = catchError(parseAndValidateAge("5")) // Age is a int
DistanceFromHome = catchError(parseAndValidatePi("3.14")) // DistanceFromHome is a float
Location = catchError(parseAndValidatePi("3.14,2.0")) //Location is a custom Struct
}

if len(errors) > 0 {
    // o, oh
}

Is this possible in Go? How can this be done easily/idiomatically?

  • 写回答

1条回答 默认 最新

  • dongningce9075 2014-12-11 09:05
    关注

    Nope; you cannot do that since Go has no parametric polymorphism for user-defined functions. All you can do is take and return interface{} and add type assertions at the call sites.

    Everything in Go is type-safe if you don't use the unsafe package, so you don't have to worry about that. A type assertion will fail at runtime instead of at compile-time, though.

    If you are willing to violate DRY, though:

    type errorList []Error
    
    func (l *errorList) addIfNotNil(err Error) {
        if err != nil {
            *l = append(*l, err)
        }
    }
    
    func (l *errorList) int(x int, err Error) int {
        l.addIfNotNil(err)
        return x
    }
    
    func (l *errorList) float32(x float32, err Error) float32 {
        l.addIfNotNil(err)
        return x
    }
    
    list := errorList([]Error{})
    data := MyStruct{
        Age: list.int(parseAndValidateAge("5")),
        DistanceFromHome: list.float32(parseAndValidatePi("3.14")),
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭