Home > Back-end >  Missing return at end of function even if conditions are exhaustive
Missing return at end of function even if conditions are exhaustive

Time:07-02

package main

import (
    "fmt"
)

func main() {
    fmt.Println(test(1, 2))
}

func test(a, b int) bool {
    if a == b {
        return true
    }
    if a > b {
        return true
    }
    if a < b {
        return false
    }
}

run above code i get the follow wrong message:

./main.go:21:1: missing return at end of function

my question is in function test, all the situation is return. why also need return at end of function.

CodePudding user response:

This is regulated by the language specifications (source):

If the function's signature declares result parameters, the function body's statement list must end in a terminating statement.

And a terminating statement is defined as:

An "if" statement in which:

  • the "else" branch is present, and
  • both branches are terminating statements.

Your if statements do not have an else branch, so your function body is missing the terminating statement, even if the conditions being tested may be exhaustive.

You must either add an explicit return at the end of the function body, or rewrite as an if-else (only else if is not enough):

func test(a, b int) bool {
    // this is a terminating statement
    if a == b {
        return true
    } else if a > b {
        return true
    } else /* a < b */ {
        return false
    }
}

However this kind of if-greater-or can be just written as:

return a >= b

CodePudding user response:

You are missing the terminating statement

To break out of your current block, you need the terminating statement. You can use a return statement or in your case an else statement. Since you are looking to terminate using the " if" statement, then you must have an else.

package main

import (
    "fmt"
)

func main() {
    fmt.Println(test(1, 2))
}

func test(a, b int) bool {
    if a == b {
        return true
    } else if a > b {
        return true
    }
    return false
}

If you want to read up about how blocks work and terminating statements I'll leave you to the official documentation: Terminating Statements, Blocks

Happy Coding!

  •  Tags:  
  • go
  • Related