gpt4 book ai didi

rust - 当赋值发生在for循环中时,使用引用分配变量如何与rust一起使用?

转载 作者:行者123 更新时间:2023-12-03 11:48:02 26 4
gpt4 key购买 nike

我才刚刚开始学习rust,还不太了解rust使用的引用系统。在下面的函数中,我试图为FizzBu​​zz编写代码,该代码根据&str的最小公倍数将结果分配给u32

fn fizzbuzz(last_num: u32) {
for i in 1..last_num+1 {
let result = if i % 15 == 0 {
"FizzBuzz"
} else if i % 3 == 0 {
"Fizz"
} else if i % 5 == 0 {
"Buzz"
} else {
&i.to_string()[..]
};
println!("{}", result);
}
}
在我的else子句中,出现以下错误:
11 |           } else if i % 5 == 0 {
| ________________-
12 | | "Buzz"
13 | | } else {
14 | | &i.to_string()[..]
| | ^^^^^^^^^^^^^ creates a temporary which is freed while still in use
15 | | };
| | -
| | |
| |_________temporary value is freed at the end of this statement
| borrow later used here
据我到目前为止对 rust 的了解,这应该不是问题,因为在从内存中释放 &i的作用域结束之前使用了 i引用。
我到底在做什么错,解决方法是什么?

最佳答案

问题不在于&i引用,而是作为临时变量i.to_string()(字符串类型)创建了新的东西,然后它被用于创建引用字符串类型的str(原始类型),该字符串类型后来由于其临时性而被销毁。意味着您正在调用不存在的东西。和Stringstr是不同的you can see the explanation here
解决此问题的最简单方法是改用String:

fn fizzbuzz(last_num: u32) {
for i in 1..last_num+1 {
let result: String = if i % 15 == 0 {
String::from("FizzBuzz")
} else if i % 3 == 0 {
String::from("Fizz")
} else if i % 5 == 0 {
String::from("Buzz")
} else {
i.to_string()
};
println!("{}", result);
}
}

但是,如果您想继续使用 str类型,可以按照以下方式进行操作:
fn fizzbuzz(last_num: u32) {
for i in 1..last_num+1 {
let wont_be_destroyed: String = i.to_string();
let mut result = &wont_be_destroyed[..];
if i % 15 == 0 {
result = &"FizzBuzz"
} else if i % 3 == 0 {
result = &"Fizz"
} else if i % 5 == 0 {
result = &"Buzz"
}
println!("{}", result);
}
}

关于rust - 当赋值发生在for循环中时,使用引用分配变量如何与rust一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63294318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com