I have read that there is no way to overload a function in Go. I mean by overloading, a way to have two functions with the same name but with different arguments.
I have seen something strange in the built-in functions of Go:
Let's suppose ch1
is a channel variable:
ch1 := make(chan string)
It is possible to read somthing from a channel like this:
result := <-ch1
But it is also possible to get a status like this:
result, status := <-ch1
So, is there is a way to overloaded a function like a built-in function?
No.
For obvious reasons this is called the comma ok idiom (not a function overload ):
result, status := <-ch1
1- Try this for Channels:
package main
import (
"fmt"
)
func main() {
ch1 := make(chan string, 1)
ch1 <- `Hi`
result, status := <-ch1
fmt.Println(result, status) // Hi true
ch1 <- `Hi`
close(ch1)
result, status = <-ch1
fmt.Println(result, status) // Hi true
result, status = <-ch1
fmt.Println(result, status) // false
}
output:
Hi true
Hi true
false
2- Try this for Maps:
package main
import (
"fmt"
)
func main() {
m := map[string]int{"One": 1, "Two": 2}
result, status := m["One"]
fmt.Println(result, status) // 1 true
result, status = m["Two"]
fmt.Println(result, status) // 2 true
result, status = m["Zero"]
fmt.Println(result, status) // 0 false
}
output:
1 true
2 true
0 false
3- Try this for interface
conversions and type assertions:
package main
import (
"fmt"
)
func main() {
var s interface{} = `One`
result, status := s.(string)
fmt.Println(result, status) // One true
i, status := s.(int)
fmt.Println(i, status) // 0 false
}
output:
One true
0 false
The Go Programming Language Specification
Built-in functions are predeclared. They are called like any other function but some of them accept a type instead of an expression as the first argument.
The built-in functions do not have standard Go types, so they can only appear in call expressions; they cannot be used as function values.
The Go programming language does not allow function overloading except for Go built-in functions. There is no way for you to overload your functions.