2.5 KiB
Which one below is not one of the logical operators of Go?
||
!=
CORRECT!
&&
2: That's the "not equal" operator. It's a comparison operator, not a logical operator.
Which one of these types is returned by a logical operator?
- int
- byte
- bool CORRECT
- float64
3: That's right. All the logical operators return an untyped bool value (true or false).
Which one of these can be used as an operand to a logical operator?
- int
- byte
- bool CORRECT
- float64
3: That's right. All the logical operators expect a bool value (or a bool expression that yields a bool value).
What does this program print?
package main
import "fmt"
func main() {
var (
on = true
off = !on
)
fmt.Println(!on && !off)
fmt.Println(!on || !off)
}
- true true
- true false
- false true CORRECT
- false false
- error
3:
!on
is false.!off
is true. So,!on && !off
is false. And,!on || !off
is true.
What does this program print?
package main
import "fmt"
func main() {
on := 1
fmt.Println(on == true)
}
- true
- false
- error CORRECT
3:
on
is int, whiletrue
is a bool. So, there's a type mismatch error here. Go is not like other C based languages where1
equals totrue
.
What does this code print?
// Note: "a" comes before "b"
a := "a" > "b"
b := "b" <= "c"
fmt.Println(a || b)
- "a"
- "b"
- true CORRECT
- false
- error
1-2: Logical operators return a bool value only.
3: Order is like so: "a", "b", "c". So,
"a" > "b"
is false."b" <= "c"
is true. So,a || b
is true.
5: There isn't an error. Strings are actually numbers, so, they're ordered and can be compared using the ordering operators.
What does the following program print?
// Let's say that there are two functions like this:
//
// `a()` which returns `true` and prints `"A"`.
// `b()` which returns `false` and prints `"B"`.
//
// Remember: Logical operators short-circuit.
_ = b() && a()
_ = a() || b()
- "BAAB"
- "BA"
- "ABBA"
- "AB"
1, 3: Remember: Logical operators short-circuit.
2: That's right.
In:
b() && a()
,b()
returns false, so, logical AND operator short-circuits and doesn't calla()
; so it prints:"B"
.Then, in:
a() || b()
,a()
returns true, so, logical OR operator short circuits and doesn't callb()
; so it prints"A"
.
4: Think again.
Example program is here.