Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Provide function return from an if statement issues

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?

like image 469
sSmacKk Avatar asked Dec 02 '22 17:12

sSmacKk


2 Answers

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())
}
like image 88
siritinga Avatar answered Dec 10 '22 23:12

siritinga


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:

  • http://golang.org/doc/go1.1#return
  • http://golang.org/ref/spec#Terminating_statements
like image 29
nvcnvn Avatar answered Dec 10 '22 22:12

nvcnvn