为什么要编译以下两段代码:
一种)
impl Rectangle {
fn can_hold(&self, other : &Rectangle) -> bool{
if self.width > other.width && self.height > other.height {
return true;
}
return false;
}
}
B)
impl Rectangle {
fn can_hold(&self, other : &Rectangle) -> bool{
if self.width > other.width && self.height > other.height {
true
}else{
false
}
}
}
但这不是:
C)
impl Rectangle {
fn can_hold(&self, other : &Rectangle) -> bool{
if self.width > other.width && self.height > other.height {
true
}
return false;
}
}
无法与错误消息一起编译
expected `()`, found `bool`
为什么编译器认为存在()
返回类型?
其实我也想知道为什么你不能做这样的事情:
D)
impl Rectangle {
fn can_hold(&self, other : &Rectangle) -> bool{
if self.width > other.width && self.height > other.height {
true
}
false
}
}
因为我认为这可以由编译器完全解析,并且意图很明确(或者不明确?)。为什么不清楚我想返回该表达式的结果。
(A)之所以起作用,是因为无论是否输入了if块,执行都会遇到一条return
语句,该语句终止该方法并返回bool
方法签名所期望的type值。
(B)之所以起作用,是因为只能输入if / else块之一,并且它们都包含一个计算为type的表达式bool
。因为在if / else之后没有更多的代码可以到达,Rust将把遇到的表达式作为方法的返回值,键入bool
方法签名所期望的值。
在(C)中,您可以true
在if
块中包含表达式。但是,如果方法是在方法内到达的最后一行代码,则该方法仅返回表达式的值。在(C)中,您拥有true
if块,然后调用return false
。所以锈看到这里面包含行true
是不是将要达到的最终线(因为没有什么可以停止执行继续后,如果块)等锈不希望在此行返回类型(因此,预计()
类型的表示没有返回类型)。如果要return true
在if块内部使用(使您回到(A)模式),那么Rust将知道该方法的执行在此处停止,并且将返回指定的值。
(D)会由于与(C)相同的原因而失败(因为true
即使输入了if块,该表达式也不是最后执行的行)。
请注意,您不需要if
或else
在此示例中,因为编写整个方法的最简单方法是这样的:
impl Rectangle {
fn can_hold(&self, other : &Rectangle) -> bool{
self.width > other.width && self.height > other.height
}
}
现在,该方法中唯一的一行是一个表达式,其计算结果为true或false,而此值就是此方法将返回的值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句