作为学习Rust的简单练习,我决定实现一个简单的二进制搜索:
pub fn binary_search(arr: &[i32], key: i32) -> usize {
let min: usize = 0;
let max: usize = arr.len();
while max >= min {
let mid: usize = (max - min) / 2 as usize;
if key == arr[mid] {
mid as usize
}
if key < arr[mid] {
min = mid + 1;
continue;
}
max = mid - 1;
}
-1 as usize
}
#[cfg(test)]
mod tests {
use super::binary_search;
#[test]
fn binary_search_works() {
let arr: [i32; …Run Code Online (Sandbox Code Playgroud) 我是 rust 的新手(来自 c/c++ 和 python 编程)所以为了学习我正在编写一些基本函数。下面我有一个阶乘函数,它接受一个有符号整数,并且有两个 if 检查它。
fn factorial(x: i32) -> i32 {
let result = if x > 1 {
x * factorial(x-1)
} else if x <= 1 {
1
};
result
}
Run Code Online (Sandbox Code Playgroud)
据我所知,if 和 else-if 块应该处理它的所有情况。但是,在编译时会引发以下错误:
error[E0317]: `if` may be missing an `else` clause
--> src/main.rs:22:12
|
22 | } else if x <= 1 {
| ____________^
23 | | 1
| | - found here
24 | | };
| |_____^ expected `()`, …Run Code Online (Sandbox Code Playgroud) 为什么以下代码在编译时会引发错误?
fn test(n: i32) -> Result<i32, &'static str> {
if n == 0 {
Err("error")
}
Ok(n + 1)
}
Run Code Online (Sandbox Code Playgroud)
以下是错误:
fn test(n: i32) -> Result<i32, &'static str> {
if n == 0 {
Err("error")
}
Ok(n + 1)
}
Run Code Online (Sandbox Code Playgroud)
下面两个版本编译没有问题。
用else声明:
fn test(n: i32) -> Result<i32, &'static str> {
if n == 0 {
Err("error")
}
else {
Ok(n + 1)
}
}
Run Code Online (Sandbox Code Playgroud)用return声明:
fn test(n: i32) -> Result<i32, &'static str> {
if n == …Run Code Online (Sandbox Code Playgroud)在C++中,我可以进行就地分配,在将变量var打印到屏幕时递增变量:
int var = 5;
std::cout << ( var += 1 ) << std::endl;
Run Code Online (Sandbox Code Playgroud)
我这样做是因为Rust没有输入/减少运算符++&--.我在Rust尝试过:
let mut counter = 0;
println!("{}", (counter += 1));
Run Code Online (Sandbox Code Playgroud)
它说:
error[E0277]: the trait bound `(): std::fmt::Display` is not satisfied
--> src/main.rs:3:20
|
3 | println!("{}", (counter += 1));
| ^^^^^^^^^^^^^^ the trait `std::fmt::Display` is not implemented for `()`
|
= note: `()` cannot be formatted with the default formatter; try using `:?` instead if you are using a format …Run Code Online (Sandbox Code Playgroud)