我应该何时在std::cmp::ordering
块中使用match
而不是使用if
/ else if
声明?可读性是唯一的区别吗?
例如:
use std::cmp::Ordering;
fn main() {
match 2.cmp(&2) {
Ordering::Less => println!("Less than 2."),
Ordering::Greater => println!("Greater than 2."),
Ordering::Equal => println!("Equal to 2."),
}
}
VS
fn main() {
if 1 < 2 {
println!("less than 2.");
} else if 1 > 2 {
println!("Greater than 2.");
} else if 1 == 2 {
println!("Equal to 2.");
}
}
答案 0 :(得分:11)
可读性是唯一的区别吗?
我会说这更像是干(不要重复自己)的事情。
如果你看第二个样本,那就太乱了:
fn main() { if 1 < 2 { println!("less than 2."); } else if 1 > 2 { println!("Greater than 2."); } else if 1 == 2 { println!("Equal to 2."); } }
else
条款。如果你搞砸了条件,它就什么都不做。else
子句,你最好还是在assert!(1 == 2)
里面放一个1 < 2
来确保它只在两者相等的情况下才会被采用(而不是因为你犯了错误)以前的条件)。1 > 2
和match
之间重复。将其与fn main() {
match 2.cmp(&2) {
Ordering::Less => println!("Less than 2."),
Ordering::Greater => println!("Greater than 2."),
Ordering::Equal => println!("Equal to 2."),
}
}
:
if
因此,match
vs if
确实是一系列不同的输出问题:
match
match
。 if
比else
/ cmp
链更易于维护。
注意:我个人认为import random
def max_pairwise_product_fast(n, a):
global fast
max_index1 = -1
for i in range(n):
if max_index1 == -1 or a[i] > a[max_index1]:
max_index1 = i
max_index2 = -1
for i in range(n):
if i != max_index1 and (max_index2 == -1 or a[i] > a[max_index2]):
max_index2 = i
fast = a[max_index1] * a[max_index2]
return fast
def max_pairwise_product(n, a):
global result
for i in range(0, n):
for j in range(i + 1, n):
if a[i] * a[j] > result:
result = a[i] * a[j]
return result
result = 0
fast = 0
while result == fast:
if __name__ == '__main__':
n = (random.randint(2, 11))
a = list(random.randint(0, 99999) for r in range(n))
assert (len(a) == n)
result = max_pairwise_product(n, a)
fast=max_pairwise_product_fast(n, a)
print(fast, result, "OK")
else:
print("Wrong Answer")
很少直接使用。它更像是一个实现设备,允许您实现一个函数来获取所有4个不等式运算符。来自C ++,这是一种解脱......