Help for the VSCode editor.
See also Assignment in the Go manual.
All the code fragments in this lab are complete mini-programs, so you can paste them into the editor and run them to see the results:
Running the code fragments
- Right click in Explorer pane to create a new file, e.g.
test.go
- Paste the question code snippet into the editor pane
- Open the terminal window and execute
go run test.go
- Re-use your
test.go
file by replacing the content with that of the next question.
-
What would be the output for the following program:
package main import "fmt" func main() { var x, y string = "foo", "bar" x += y fmt.Println(x) }
- foobar
- foo
- error
- bar
Reveal
foobar
+=
is "add and assign", and is equivalent tox = x + y
. When you add two strings, the result is the concatenation of the strings. -
What would be the output for the following program:
package main import "fmt" func main() { var x, y int = 27, 7 x /= y fmt.Println(x) }
- 6
- 3
- error
- 6.00
Reveal
3
/=
is "divide and assign", and is equivalent tox = x / y
. Since we have two integers, then an integer division is performed and the remainder is discarded:27 / 7 = 3 r6
-
What would be the output for the following program:
package main import "fmt" func main() { var x, y float64 = 27.9, 7.0 x -= y fmt.Println(x) x += y fmt.Println(x) }
- 27.9
20.9 - 20.9
27.9 - 20.9
7.9 - 27.9
9.0
Reveal
20.9
27.9x -= y
... x = 27.9 - 7.0 = 20.9, thenx += y
... x = 20.9 + 7.0 = 27.9
- 27.9
-
What would be the output for the following program:
package main import "fmt" func main() { var x, y int = 100,9 x /= y fmt.Println(x) x %= y fmt.Println(x) }
- 2
2 - 11
2 - 2
11 - 11
11
Reveal
11
2x /= y
... x = 100 / 9 = 11. Remember this is an integer division so the remainder is discarded, thenx %= y
... x = 11 % 9 = 2.x
is now 11 from the previous division assignment. Remainder of 11 divided by 2 is 2.
- 2
-
Which of these operator assigns the remainder of the division x
/=
*=
%=
\=
Reveal
%=
This is the modulo (remainder) assignment operator.
/=
is divide assign*=
is multiply assign\=
is a syntax error and won't compile.