3.2 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).
Which expression below equals to the sentence below?
"age is equal or above 15 and hair color is yellow"
age > 15 || hairColor == "yellow"
age < 15 || hairColor != "yellow"
age >= 15 && hairColor == "yellow"
CORRECTage > 15 && hairColor == "yellow"
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:
//
// super() which returns true and prints "super ".
// duper() which returns false and prints "duper ".
//
// Remember: Logical operators short-circuit.
package main
import "fmt"
func main() {
_ = duper() && super()
_ = super() || duper()
}
// Don't mind about these functions.
// Just focus on the problem.
// These are here just for you to understand it better.
func super() bool {
fmt.Print("super ")
return true
}
func duper() bool {
fmt.Print("duper ")
return false
}
- "super duper super duper "
- "duper super " CORRECT
- "duper super super duper "
- "super duper "
1, 3: Remember: Logical operators short-circuit.
2: That's right.
In:
duper() && super()
,duper()
returns false, so, logical AND operator short-circuits and doesn't callsuper()
; so it prints:"duper "
.Then, in:
super() || duper()
,super()
returns true, so, logical OR operator short circuits and doesn't callduper()
; so it prints"super "
.
4: Think again.
Example program is here.