有几个问题似乎与我遇到的问题有关.例如,请看这里和这里.基本上我正在尝试String在本地函数中构建一个函数,但是然后将其作为一个函数返回&str.切片不起作用,因为寿命太短.我无法str直接在函数中使用,因为我需要动态构建它.但是,我也不想返回a,String因为一旦它构建完成,它进入的对象的性质就是静态的.有没有办法让我的蛋糕也吃?
这是一个最小的非编译复制:
fn return_str<'a>() -> &'a str {
let mut string = "".to_string();
for i in 0..10 {
string.push_str("ACTG");
}
&string[..]
}
Run Code Online (Sandbox Code Playgroud) 我is_prime在Rust中编写了一个函数,我的印象是简单的写作true相当于return true;,但在我的函数中并非如此:
fn is_prime(number: i64) -> bool {
for i in 2i64..number {
if number % i == 0 && i != number {
false
}
}
true
}
Run Code Online (Sandbox Code Playgroud)
这会给我错误:
error[E0308]: mismatched types
--> src/lib.rs:4:13
|
4 | false
| ^^^^^ expected (), found bool
|
= note: expected type `()`
found type `bool`
Run Code Online (Sandbox Code Playgroud)
替换true和false使用return true;/ return false;工作,但为什么使用以前不编译?
我试图在Rust中实现fizzbuzz并且失败了一些神秘的错误:
fn main() {
let mut i = 1;
while i < 100 {
println!(
"{}{}{}",
if i % 3 == 0 { "Fizz" },
if i % 5 == 0 { "Buzz" },
if !(i % 3 == 0 || i % 5 == 0) { i },
);
i += 1;
}
}
Run Code Online (Sandbox Code Playgroud)
错误:
error: mismatched types: expected `()` but found `&'static str` (expected () but found &-ptr)
if i % 3 == 0 { "Fizz" },
^~~~~~~~~~ …Run Code Online (Sandbox Code Playgroud) 我是 Rust 编程新手。我想用递归实现合并排序。这是我的代码:
fn merge(a: &mut Vec<u32>, b: &mut Vec<u32>) -> Vec<u32> {
let mut temp: Vec<u32> = Vec::new();
println!("The digit is {}", a[0]);
while a.len() > 0 && b.len() > 0 {
if a[0] > b[0] {
temp.push(a[0]);
a.pop();
} else {
temp.push(b[0]);
b.pop();
}
}
while a.len() > 0 {
temp.push(a[0]);
a.pop();
}
while b.len() > 0 {
temp.push(b[0]);
b.pop();
}
temp
}
fn merge_sort(v: &mut Vec<u32>) -> Vec<u32> {
println!("The divided vector is: {:?}", v);
let n …Run Code Online (Sandbox Code Playgroud)