gpt4 book ai didi

Rust — 为什么这里有警告 "value captured by ` online` is never read"?

转载 作者:行者123 更新时间:2023-12-05 04:22:10 26 4
gpt4 key购买 nike

为什么 Rust 编译器会发出此警告?

value captured by online is never read

use std::{thread, time::Duration};
use rand::Rng;

fn main() {
let mut online = false;

thread::spawn(move || {
loop {
if let Some(_) = get_rand_option() {
online = true; // why is there a warning here?
} else {
online = false;
}

if online { // is the value not being read here?
println!("Yee");
} else {
println!("...");
}
}
});

thread::sleep(Duration::from_millis(100000));
}

fn get_rand_option() -> Option<i32> {
rand::thread_rng().gen::<Option<i32>>()
}

最佳答案

Rust 足够聪明,知道您将在使用该变量之前对其进行初始化,因此它会告诉您在此之前为其赋值是多余的。我还将变量声明移动到闭包内,否则它会永久移动到闭包内。

请注意,对于这个最小的示例,您最好在循环内声明 online,因为您永远不会跳出它或使用上一次迭代的值:let online =如果让……

use std::{thread, time::Duration};
use rand::Rng;

fn main() {

thread::spawn(|| {
let mut online: bool;
loop {
// using the fact that ‘if let’ is an expression
online = if let Some(_) = get_rand_option() {
true
} else {
false
};

if online {
println!("Yee");
} else {
println!("...");
}
}
});

thread::sleep(Duration::from_millis(100000));
}

fn get_rand_option() -> Option<i32> {
rand::thread_rng().gen::<Option<i32>>()
}

关于Rust — 为什么这里有警告 "value captured by ` online` is never read"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74036684/

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