package main
import “fmt”
func canidrink(age int) bool {
if koreanAge := age + 2; koreanAge < 18 {
return false
}
return true
}
func main() {
fmt.Println(canidrink(16))
}
package main
import “fmt”
func canidrink(age int) bool {
if koreanAge := age + 2; koreanAge < 18 {
return false
}
return true
}
func main() {
fmt.Println(canidrink(16))
}
When you pass 16 to canidrink, age is 16 and after sum 2, koreanAge = 18 and this value is not less than 18, it is equal, so the if clause is not executed and goes to the else clause…
Thank you
i fixed Conditional
func canidrink(age int) bool {
if koreanAge := age + 2; koreanAge < 19 {
return false
}
return true
Or you could do it like this:
func canIDrinkInKorea(age int) bool {
if koreanAge := age + 2; koreanAge <= 18 {
return false
}
return true
}
Note the less than or equal sign, <= . It is slightly more readable, since what you want to compare with is 18, and not 19.
This could be written more compact without magic numbers but type safety.
type age uint
const legalDrinkingAgeInKorea age = 16
func canIDrinkInKorea(theAge age) bool {
// No magic number here!
return theAge > legalDrinkingAgeInKorea
}
Using a type age
prevents passing an int
that is not an age. This will not compile:
var currentYear = 2020
fmt.Println(canIDrinkInKorea(currentYear))
There is a reason why people don’t use unsigned integer types to validate the range of an integer domain. It doesn’t work.
package main
import (
"fmt"
"math"
)
type Age uint
const legalDrinkingAgeInKorea Age = 16
func canIDrinkInKorea(theAge Age) bool {
return theAge > legalDrinkingAgeInKorea
}
func main() {
for _, age := range []int{
-1, 0, 15, 16, 17, 18, 19, math.MaxInt32, math.MinInt32,
} {
fmt.Println(age, canIDrinkInKorea(Age(age)))
}
}
-1 true
0 false
15 false
16 false
17 true
18 true
19 true
2147483647 true
-2147483648 true
This may be an argument against using unit
here. But my point is to use a specific type.