compiler/fight-with-compiler/lifetime/loop #1054
Replies: 7 comments 1 reply
-
👍🏻 first, |
Beta Was this translation helpful? Give feedback.
-
“唯一满足条件的就是:k的生命周期等于循环生命周期。” |
Beta Was this translation helpful? Give feedback.
-
use rand::{thread_rng, Rng};
#[derive(Debug, PartialEq)]
enum Tile {
Empty,
}
fn random_empty_tile(arr: &[Tile]) -> &Tile {
loop {
let l = arr.len();
let i = thread_rng().gen_range(0..1);
let tile = &arr[i];
if &Tile::Empty == tile {
return &tile;
}
}
} |
Beta Was this translation helpful? Give feedback.
-
对这句话存有疑问,编译器并不会认为k的生命周期小于循环吧。
return 后 k 可以继续使用。 |
Beta Was this translation helpful? Give feedback.
-
这个例子和 niko's NLL 这篇的第三个例子有点像。 |
Beta Was this translation helpful? Give feedback.
-
这种中间变量的错误我在线程间传递 thread::spawn(move || {
for notes in STEP2_NOTES2 {
for notes in notes.iter() {
for note in notes {
println!("{:?}", *note as u8);
play_note(unsafe { ptr_clone.0.as_mut().unwrap() }, *note as u8, 1);
}
}
}
}), 看似没问题,结果 error[E0277]: `*mut MidiOutputConnection` cannot be sent between threads safely
--> src/play.rs:78:23
|
78 | thread::spawn(move || {
| ------------- ^------
| | |
| _________|_____________within this `{closure@src/play.rs:78:23: 78:30}`
| | |
| | required by a bound introduced by this call
79 | | for notes in STEP2_NOTES2 {
80 | | for notes in notes.iter() {
81 | | for note in notes {
... |
86 | | }
87 | | }),
| |_________^ `*mut MidiOutputConnection` cannot be sent between threads safely
|
= help: within `{closure@src/play.rs:78:23: 78:30}`, the trait `Send` is not implemented for `*mut MidiOutputConnection`
note: required because it's used within this closure
--> src/play.rs:78:23
|
78 | thread::spawn(move || {
| ^^^^^^^
note: required by a bound in `spawn`
--> /home/star/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/thread/mod.rs:685:8
|
682 | pub fn spawn<F, T>(f: F) -> JoinHandle<T>
| ----- required by a bound in this function
...
685 | F: Send + 'static,
| ^^^^ required by this bound in `spawn`
For more information about this error, try `rustc --explain E0277`. 然后只需要引入中间变量 thread::spawn(move || {
let temp = ptr_clone;
for notes in STEP2_NOTES2 {
for notes in notes.iter() {
for note in notes {
println!("{:?}", *note as u8);
play_note(unsafe { temp.0.as_mut().unwrap() }, *note as u8, 1);
}
}
}
}), Checking midi_play v0.1.0 (/code/star/midi_play)
Finished dev [unoptimized + debuginfo] target(s) in 0.10s 就通过了 |
Beta Was this translation helpful? Give feedback.
-
"如果一个引用值从函数的某个路径提前返回了,那么该借用必须要在函数的所有返回路径都合法"这句话才是经典 |
Beta Was this translation helpful? Give feedback.
-
compiler/fight-with-compiler/lifetime/loop
https://course.rs/compiler/fight-with-compiler/lifetime/loop.html
Beta Was this translation helpful? Give feedback.
All reactions