https://gobyexample.com
also https://go.dev/tour/welcome/1
all working except: https://gobyexample.com/timers
sections (future put an outlined based section.
In my opinion kind of dumb, https://stackoverflow.com/questions/6986944/does-the-go-language-have-function-method-overloading
why have a type system and no function overloading?
func plusPlus(a, b, c int) int {
return a + b + c
}
func plusPlus(a, b, c string) int {
fmt.Println(a)
fmt.Println(b)
fmt.Println(a)
return 4
}
// fails
type any = interface{}
func plusPlus(a, b, c any) any {
return a
}
// works
type Number interface {
int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | float32 | float64
}
type all = string | number Number | type | bool | error
func Sum[number Number](a number, b number) number {
return a + b
}
// works but a + b would fail because it now is not of type number.
type All interface {
// https://kuree.gitbooks.io/the-go-programming-language-report/content/3/text.html
// string, numeric type, bool, and error
rune | string | int | int8 | int16 | int64 | uint | uint8 | uint16 | uint32 | uint64 | float32 | float64 | bool
// https://go.dev/ref/spec#Predeclared_identifiers
// any bool byte comparable
// complex64 complex128 error float32 float64
// int int8 int16 int32 int64 rune string
// uint uint8 uint16 uint32 uint64 uintptr
}
func plusPlus[number All](a, b, c number) number {
return a + b + c
}
// fails ... ./prog.go:40:9: invalid operation: operator + not defined on a (variable of type number constrained by All)
func alt(a, b int) int {
return a + b
}
func plusPlus(a, b, c any) {
switch t := a.(type) {
case bool:
return
case int:
fmt.Printf("is an int %T\n", t)
var result = a.(int) + b.(int)
fmt.Println("1+2+3 =", result)
// return alt(a.(int), b.(int))
default:
fmt.Printf("Don't know type %T\n", t)
}
// return 3
return
}
// works, uses type assertions https://go.dev/tour/methods/15
Uh oh!
There was an error while loading. Please reload this page.