I'm having trouble returning a function's expected return statement from within an if statement in golang.
I have provided the code below:
package main
import (
"fmt"
)
func random() string {
var x = "return"
if x == "return" {
return x
}
}
func main() {
fmt.Println(random())
}
Shouldn't the main function print out the string value returned by the random function?All i get is
go.go:13: missing return at end of function
Does anybody have a clue how to make this happen?
You have to include a return
at the end, even if it is never used, if the function returns a value:
http://play.golang.org/p/XFsPL2G15R
func random() string {
var x = "return"
if x == "return" {
return x
}
return ""
}
func main() {
fmt.Println(random())
}
In Go 1.1, you don't need to add return at the end of function all the time, but you need a Terminating statement, this code should work: http://play.golang.org/p/fNiijqNHbt
func random() string {
var x = "return"
if x == "return" {
return x
} else {
return "else"
}
}
func main() {
fmt.Println(random())
}
For more infomation, see:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With