golang / tour

[mirror] A Tour of Go
BSD 3-Clause "New" or "Revised" License
1.54k stars 522 forks source link

tour: Syntax error when the else statement is misplaced #442

Open valaparthvi opened 6 years ago

valaparthvi commented 6 years ago

Context: https://tour.golang.org/flowcontrol/7 The "}" closing brace of if statement must be immediately followed by an else statement if any. Writing else on a separate line(like we do in Python, C, Java, etc) will generate a SyntaxError in Go. Example:

package main

import (
    "fmt"
    "math"
)

func pow(x, n, lim float64) float64 {
    if v := math.Pow(x, n); v < lim {
        return v
    }
    else {                                                 // misplaced "else" statement
        fmt.Printf("%g >= %g\n", v, lim)
    }
    // can't use v here, though
    return lim
}

func main() {
    fmt.Println(
        pow(3, 2, 10),
        pow(3, 3, 20),
    )
}

Output: prog.go:12:2: syntax error: unexpected else, expecting }

WheeskyJack commented 6 years ago

Hi, Above behavior is expected one. "else" statement should be in same line as the closing brace of corresponding "if". Similarly, opening brace of if should be in same line as "if". Otherwise running such code should generate the error. However, opening brace of else can be in the new line. Its always good idea to run go fmt on the code before running the code to format the code as per the go standards and to catch any possible syntax errors. BR.

valaparthvi commented 6 years ago

I understand that it's the expected behavior. But what I meant was, it would be helpful if that was mentioned in the tutorial.

ALTree commented 6 years ago

Thanks for the report.

In general, I think that slide could use a little more text. It's the one that introduces the else block and it says almost nothing about it.

JackMead commented 6 years ago

Newb trying Hacktoberfest, tiny change but appreciate pointers nonetheless!

Ekasa02 commented 2 years ago

image bagaimana cara agar output sesuai ketentuan dalam README