Is there a way to use one function using a generic parameter instead of having two functions as shown below? I have Java background and looking for a way to have something like this
//Java
public Something doSomething(T val)
//Go
func (l *myclass) DoSomethingString(value string) error {
test := []byte[value]
// do something with test
return err
}
func (l *myclass) DoSomethingInt(value int64) error {
test := []byte[value]
// do something with test
return err
}
Unfortunately, Go has no generics and no overloading. You can use a parameter of type interface{}
and switch over it's real type:
func (*Test) DoSomething(p interface{}) {
switch v := p.(type) {
case int64:
fmt.Println("Got an int:", v)
case string:
fmt.Println("Got a string", v)
default:
fmt.Println("Got something unexpected")
}
}