Alternative for function overloading in Go?

只谈情不闲聊 提交于 2019-12-22 03:50:58

问题


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


回答1:


Neither function overloading nor optional arguments are directly supported. You could work around them building your own arguments struct. I mean like this (untested, may not work...) EDIT: now tested...

package main

    import "fmt"

    func main() {
        args:=NewMyArgs("a","b") // filename is by default "c"
        args.SetFileName("k")

        ret := Compresser(args)
        fmt.Println(ret)
    }

    func Compresser(args *MyArgs) string {
        return args.dstFilePath + args.srcFilePath + args.fileName 
    }

    // a struct with your arguments
    type MyArgs struct 
    {
        dstFilePath, srcFilePath, fileName string 
    }

   // a "constructor" func that gives default values to args 
    func NewMyArgs(dstFilePath string, srcFilePath string) *MyArgs {
        return &MyArgs{
              dstFilePath: dstFilePath, 
              srcFilePath:srcFilePath, 
              fileName :"c"}
    }

    func (a *MyArgs) SetFileName(value string){
      a.fileName=value;
    }



回答2:


The idiomatic answer to optional parameters in Go is wrapper functions:

func do(a, b, c int) {
    // ...
}

func doSimply(a, b) {
    do(a, b, 42)
}

Function overloading was intentionally left out, because it makes code hard(er) to read.




回答3:


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("<ul>")    
  for _,it := range things {
    fmt.Printf("    <li>%v</li>\n", it)
  }    
  fmt.Println("</ul>")
}



回答4:


An approach I use sometime for constructing an object using New methods having different arguments is to have a "flavor" pseudo type. You can try it on the Go Playground https://play.golang.org/p/5To5AcY-MRe

package main

import "fmt"

type flavorA struct{}
type flavorB struct{}

var FlavorA = flavorA{}
var FlavorB = flavorB{}

type Something struct {
    i int
    f float64
}

func (flavor flavorA) NewSomething(i int) *Something {
    return &Something{i:i, f:0.0}
}

func (flavor flavorB) NewSomething(f float64) *Something {
    return &Something{i:0, f:f}
}

func main() {
    fmt.Println(FlavorA.NewSomething(1), FlavorB.NewSomething(2))
}


来源:https://stackoverflow.com/questions/13028486/alternative-for-function-overloading-in-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!