Skip to content

Latest commit

 

History

History
170 lines (118 loc) · 3.44 KB

04-assignment-operators.md

File metadata and controls

170 lines (118 loc) · 3.44 KB

Lab: Assignment Operators

Take me to the lab!

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
  1. Right click in Explorer pane to create a new file, e.g. test.go
  2. Paste the question code snippet into the editor pane
  3. Open the terminal window and execute go run test.go
  4. Re-use your test.go file by replacing the content with that of the next question.

Questions

  1. 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 to x = x + y. When you add two strings, the result is the concatenation of the strings.

  2. 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 to x = x / y. Since we have two integers, then an integer division is performed and the remainder is discarded: 27 / 7 = 3 r6

  3. 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.9

    • x -= y ... x = 27.9 - 7.0 = 20.9, then
    • x += y ... x = 20.9 + 7.0 = 27.9
  4. 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
    2

    • x /= y ... x = 100 / 9 = 11. Remember this is an integer division so the remainder is discarded, then
    • x %= y ... x = 11 % 9 = 2. x is now 11 from the previous division assignment. Remainder of 11 divided by 2 is 2.
  5. 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.