Alternative for function overloading in Go?

后端 未结 4 1540
不知归路
不知归路 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 17:12

    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))
    }
    

提交回复
热议问题