dongtigai3875 2016-08-01 03:21
浏览 118

是否可以在Golang中创建类型通用(模板)函数

I'm new to go - just playing with it - but I've written a command line tool - I call about 30 different functions that return x, err. In every case - what I want to do is just panic if there is an error - basically everything works perfectly, or the whole thing fails.

I know there's template.Must( t Template*, err Error) Template* - and I know I can make a check(something interface{}, err Error) interface{} - but to use it I've gotta do a type cast, which is nasty.

Is it in any way possible to make a sort of generic function panicIfError such that I can do something like

 x := panicIfError( ioutil.ReadFile( fileName )) 

and have x come out with the right type?

(I've seen lots of people put the if on the same line - to my mind that sacrifices too much readability - currently my only solution is to make an overload of panicIfError for every single type I use, which is not ideal)

  • 写回答

1条回答 默认 最新

  • dongtangyi8962 2016-08-01 06:10
    关注

    The best you can do is declare it to return a value of type interface{}, but that's not what you're looking for (you'd need type assertion to get values of other types out of it).

    You want your panicIfError() function to return different concrete types. That's not possible in Go.

    See related topic in FAQ: Why does Go not have generic types?

    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答