dongxu8533486 2015-12-22 00:33
浏览 55
已采纳

如何编写一个可以接受多种类型之一的函数?

I'm trying go for a small project and tried to write these functions:

func fatal(reason string) {
    println(reason)
    os.Exit(1)
}

func fatal(err error) {
    fatal(err.Error())
}

After digging about a bit and finding this answer, which referenced the docs on overloading I realised that what I was trying to do was illegal in go.

What I want is a simple api that allows me to call fatal with either a string or an error in order to simplify my logic. How do I achieve this or a similar goal?

It would feel inelegant to have func fatal(reason string) along with func fatalErr(err error), is that what's needed? Am I missing a different feature of the language that allows me to do what I want?

  • 写回答

3条回答 默认 最新

  • dounao5856 2015-12-22 00:42
    关注

    The most common way to do this would be to define the method as func fatal(err interface{}) then do type assertions or use a type switch within it's body to handle each of the different types. If I were coding for your example it would look like this;

    func fatal(err interface{}) {
         if v, ok := err.(string); ok {
             fmt.Println(v)
         }
         if v, ok := err.(error); ok {
              fmt.Println(v.Error())
         } else {
            // panic ?
         }
    }
    

    Also; here's a quick read about type switches and assertions that may be helpful; http://blog.denevell.org/golang-interface-type-assertions-switch.html You can also check out effective-go as it has sections on both features.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?