Go中函数重载的替代方法?

是否可以使用Golang以类似的方式工作,例如函数重载或C#中的可选参数?还是另一种方式?


富国沪深
浏览 233回答 3
3回答

郎朗坤

Go中可选参数的惯用答案是包装函数:func do(a, b, c int) {    // ...}func doSimply(a, b) {    do(a, b, 42)}有意避免了函数重载,因为它使代码难以阅读。

饮歌长啸

有一些提示,这里使用可变参数,例如:sm1 := Sum(1, 2, 3, 4) // = 1 + 2 + 3 + 4 = 10sm2 := Sum(1, 2) // = 1 + 2 = 3sm3 := Sum(7, 1, -2, 0, 18) // = 7 + 1 + -2 + 0 + 18 = 24sm4 := Sum() // = 0func Sum(numbers ...int) int {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; n := 0&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; for _,number := range numbers {&nbsp; &nbsp; &nbsp; &nbsp; n += number&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; return n}或...interface{}任何类型:Ul("apple", 7.2, "BANANA", 5, "cHeRy")func Ul(things ...interface{}) {&nbsp; fmt.Println("<ul>")&nbsp; &nbsp;&nbsp;&nbsp; for _,it := range things {&nbsp; &nbsp; fmt.Printf("&nbsp; &nbsp; <li>%v</li>\n", it)&nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; fmt.Println("</ul>")}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go