Created
October 19, 2017 13:13
-
-
Save inancgumus/73bff9e40cfd18811710ed69e1f4bfef to your computer and use it in GitHub Desktop.
imitating function overloading in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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