tour icon indicating copy to clipboard operation
tour copied to clipboard

tour: Syntax error when the else statement is misplaced

Open valaparthvi opened this issue 7 years ago • 6 comments

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 }

valaparthvi avatar Mar 25 '18 13:03 valaparthvi

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.

WheeskyJack avatar Apr 15 '18 12:04 WheeskyJack

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

valaparthvi avatar Apr 15 '18 12:04 valaparthvi

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.

ALTree avatar Jul 04 '18 08:07 ALTree

Newb trying Hacktoberfest, tiny change but appreciate pointers nonetheless!

JackMeadDev avatar Oct 10 '18 18:10 JackMeadDev

image bagaimana cara agar output sesuai ketentuan dalam README

Ekasa02 avatar Oct 07 '22 16:10 Ekasa02