Skip to content
AgileLogics
4 min read

Operators

Prerequisites: Type conversion

Syntax

  • Arithmetic: + - * / % (+ also joins strings)
  • Comparison: == != < <= > >=
  • Logical: && (and), || (or), ! (not)
  • Assignment: = += -= *= /= %=
  • Increment/decrement: x++ and x--

Example

package main

import "fmt"

func main() {
    a, b := 7, 2

    fmt.Println(a+b, a-b, a*b, a/b, a%b)
    fmt.Println(7.0 / 2)
    fmt.Println(a > b, a == b, a != b)
    fmt.Println(a > 5 && b > 5, a > 5 || b > 5, !(a > b))

    a++
    a += 10
    fmt.Println(a)

    first := "Go"
    fmt.Println(first + "pher")
}

Expected output

9 5 14 3 1
3.5
true false true
false true false
18
Gopher

Common mistakes

  • Forgetting that dividing two integers truncates: 7 / 2 is 3.
  • Using x++ as an expression. In Go, ++ and -- are statements, so y := x++ and fmt.Println(x++) don't compile, and there is no prefix form (++x).
  • Looking for a ternary operator (cond ? a : b). Go doesn't have one — write an if/else instead.
  • Comparing values of different types (int vs float64) — a compile error until you convert one side.

Practice

A video is 3 hours and 25 minutes long. Using hours := 3 and minutes := 25, print the total length in seconds.

Show solution
package main

import "fmt"

func main() {
    hours := 3
    minutes := 25
    seconds := hours*3600 + minutes*60
    fmt.Println(seconds) // 12300
}