Appearance
if1: exercises/if/if1.rs
题目
rust
// if1.rs
//
// Execute `rustlings hint if1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
pub fn bigger(a: i32, b: i32) -> i32 {
// Complete this function to return the bigger number!
// Do not use:
// - another function call
// - additional variables
}
// Don't mind this for now :)
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ten_is_bigger_than_eight() {
assert_eq!(10, bigger(10, 8));
}
#[test]
fn fortytwo_is_bigger_than_thirtytwo() {
assert_eq!(42, bigger(32, 42));
}
}
题目解析
我们从fn bigger(a: i32, b: i32) -> i32
函数里面的注释看,题目是要求我们补全这个函数,并返回最大值。但也有两个要求:
- 不要有别的函数调用
- 不要有新增的变量
这里我们直接比较参数a
和b
的大小即可,如果a > b
,那么返回a
,否则返回b
:
rust
pub fn bigger(a: i32, b: i32) -> i32 {
// Complete this function to return the bigger number!
// Do not use:
// - another function call
// - additional variables
if a > b {
a
} else {
b
}
}
也可以这样修改:
rust
pub fn bigger(a: i32, b: i32) -> i32 {
// Complete this function to return the bigger number!
// Do not use:
// - another function call
// - additional variables
if a > b {
return a;
}
return b;
}
也可以这样修改:
rust
pub fn bigger(a: i32, b: i32) -> i32 {
// Complete this function to return the bigger number!
// Do not use:
// - another function call
// - additional variables
if a > b {
return a;
}
b
}
但是不能这样修改:❌❌❌❌❌❌❌
rust
pub fn bigger(a: i32, b: i32) -> i32 {
// Complete this function to return the bigger number!
// Do not use:
// - another function call
// - additional variables
if a > b {
a
}
b
}
因为根据之前函数的知识,当表达式用作函数返回值时,只有最后一个表达式会被当作函数的返回值,在这里也就是b
。
报错信息如下:
txt
⚠️ Compiling of exercises/if/if1.rs failed! Please try again. Here's the output:
error[E0308]: mismatched types
--> exercises/if/if1.rs:13:9
|
12 | / if a > b {
13 | | a
| | ^ expected `()`, found `i32`
14 | | }
| |_____- expected this to be `()`
|
help: you might have meant to return this value
|
13 | return a;
| ++++++ +
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.