Skip to content

Instantly share code, notes, and snippets.

@inancgumus
Created October 19, 2017 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inancgumus/73bff9e40cfd18811710ed69e1f4bfef to your computer and use it in GitHub Desktop.
Save inancgumus/73bff9e40cfd18811710ed69e1f4bfef to your computer and use it in GitHub Desktop.
imitating function overloading in go
package main
import (
"fmt"
)
func main() {
// imitating func overloading in Go
// this example uses this:
// https://golang.org/doc/effective_go.html#interface_conversions
// sum integers with the same function
// output: 3
fmt.Println(sum(1, 2))
// sum float64s with the same function
// output: 6.1
fmt.Println(sum(3.7, 2.4))
// exercise: should have a proper err logic instead of returning nil.
}
func sum(a interface{}, b interface{}) interface{} {
switch a.(type) {
// check for ints
case int:
if bint, ok := b.(int); !ok {
return nil
} else {
aint, _ := a.(int)
return sumInt(aint, bint)
}
// check for floats
case float64:
if bfloat, ok := b.(float64); !ok {
return nil
} else {
afloat, _ := a.(float64)
return sumFloat64(afloat, bfloat)
}
}
return nil
}
func sumInt(a int, b int) int {
return a + b
}
func sumFloat64(a float64, b float64) float64 {
return a + b
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment