like in js we can do
function demo(temp = 'hello'){
console.log(temp)
}
demo()
in demo function parameter is kind of optional, if we don’t pass parameter it will default to hello
like in js we can do
function demo(temp = 'hello'){
console.log(temp)
}
demo()
in demo function parameter is kind of optional, if we don’t pass parameter it will default to hello
func demo(greeting string) {
fmt.Println(greeting)
}
func demoWithDefault() {
demo("hello")
}
This is how you do it in Go. Another way was through variadic arguments, but that is far less idiomatic for this usecase:
func demo(g string...) {
switch len(g) {
case 0: fmt.Println("Hello")
case 1: fmt.Println(g[0])
default: panic("too many arguments")
}
And another alternativ was by using pointer and nil
:
func demo(g *string) {
if g == nil {
g = "Hello"
}
fmt.Println(g)
}
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.