在这个“去旅行”示例中,收益如何运作?

this is my first week learning Go. I am checking Tour of Go and in the code in https://tour.golang.org/flowcontrol/5 I don't understand how return is working inside sqrt() function.

func sqrt(x float64) string {
    if x < 0 {
        return sqrt(-x) + "i"
    }
    return fmt.Sprint(math.Sqrt(x))
}

I understand the code with a else clause like this

func sqrt(x float64) string {
            if x < 0 {
                return sqrt(-x) + "i"
            }else{
            return fmt.Sprint(math.Sqrt(x))}
        }

this code is executed without problems, but the golint in VsCode suggests me to drop the else clause. Does return sqrt(-x) + "i" inside the if ends executing the function or how is it exactly working? Thanks in advance.

As with most (if not all?) the first return statement the compiler hits will exit the function and not continue.

It's warning reported by go linter. Code underneath is valid.

func sqrt(x float64) string {
    if x < 0 {
        return sqrt(-x) + "i"
    }

    return fmt.Sprint(math.Sqrt(x))
}

This one below is also valid, but will generate some warning.

func sqrt(x float64) string {
    if x < 0 {
        return sqrt(-x) + "i"
    } else {
        return fmt.Sprint(math.Sqrt(x))
    }
}

Basically if there is if statement and the body contains return statement, better not to use else block.

The Go Programming Language Specification

Return statements

A "return" statement in a function F terminates the execution of F, and optionally provides one or more result values. Any functions deferred by F are executed before F returns to its caller.


The specification defines the language. return terminates the function.


Go Code Review Comments

Indent Error Flow

Try to keep the normal code path at a minimal indentation, and indent the error handling, dealing with it first. This improves the readability of the code by permitting visually scanning the normal path quickly. For instance, don't write:

if err != nil {
  // error handling
} else {
  // normal code
}

Instead, write:

if err != nil {
  // error handling
  return // or continue, etc.
}
// normal code

While either will work, as a matter of style, remove the unnecessary else and indentation. It's a similar to error flow indentation.