golang / tour

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

tour: briefly explain += operator in flowcontrol/1 #436

Open RegevTripp opened 6 years ago

RegevTripp commented 6 years ago

Context: https://tour.golang.org/flowcontrol/1

Build version go1.10.

Both the online tour and the one I've downloaded which is run on my native machine (MacOS High Sierra 10.13.3), show that the output of the for loop below is the integer 45:

package main

import "fmt"

func main() { sum := 0 for i := 0; i < 10; i++ { sum += i } fmt.Println(sum) }

Where the output should be:

0 1 2 3 4 5 6 7 8 9

I am unsure if this issue has been flagged before, but it could be disruptive for new comers with no prior programming experience.

WheeskyJack commented 6 years ago

Hi, the output given by the tour is correct one. "sum+=i" is short hand notation for "sum=sum+i". Hence, the for loop in code is adding all the integers from 0 to 9 and storing it in variable sum. And once for loop is over, it is printing the final sum. I am guessing you are confusing "+=" notation with the append() functionality. Following is the code snippet for your expected output: https://play.golang.org/p/CxXI7Y-soEV BR.

ALTree commented 6 years ago

The += operator is introduced in https://tour.golang.org/flowcontrol/1 without explanation, and AFAIK it's not explained any of the lessons before... we could add a brief explanation here.