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?

    评论

报告相同问题?