三元运算符的格式:
a ? b : c
a 是条件表达式,如果条件 a 为真,就执行 b;如果条件 a 为假,就执行 c
二选一
julia> println(1 < 2 ? "1 is smaller than 2" : "1 is bigger than 2") 1 is smaller than 2 julia> println(1 > 2 ? "1 is smaller than 2" : "1 is bigger than 2") 1 is bigger than 2
三选一
julia> f(x, y) = println(x < y ? "x is smaller than y" : x > y ? "x is bigger than y" : "x is equal to y") f (generic function with 1 method) julia> f(1, 2) x is smaller than y julia> f(2, 1) x is bigger than y julia> f(1, 1) x is equal to y
: 前后的表达式,只有在对应条件表达式为 true 或 false 时才执行
julia> f(x) = (println(x); x) f (generic function with 2 methods) julia> 1 < 2 ? f("yes") : f("no") yes "yes" julia> 1 > 2 ? f("yes") : f("no") no "no"