Alternative for function overloading in Go?

后端 未结 4 1916
不知归路
不知归路 2021-02-19 16:14

Is it possible to work similar way like the function overloading or optional parameter in C# using Golang? Or maybe an alternative way?

4条回答
  •  清歌不尽
    2021-02-19 16:57

    There are some hints here using variadic arguments, for example:

    sm1 := Sum(1, 2, 3, 4) // = 1 + 2 + 3 + 4 = 10
    sm2 := Sum(1, 2) // = 1 + 2 = 3
    sm3 := Sum(7, 1, -2, 0, 18) // = 7 + 1 + -2 + 0 + 18 = 24
    sm4 := Sum() // = 0
    
    func Sum(numbers ...int) int {    
        n := 0    
        for _,number := range numbers {
            n += number
        }    
        return n
    }
    

    Or ...interface{} for any types:

    Ul("apple", 7.2, "BANANA", 5, "cHeRy")
    
    func Ul(things ...interface{}) {
      fmt.Println("
      ") for _,it := range things { fmt.Printf("
    • %v
    • \n", it) } fmt.Println("
    ") }

提交回复
热议问题