Concurrency #2
https://doc.rust-lang.org/book/concurrency.html
並行処理続き。channelについて。rx
からtx
にデータが渡るまで、tx
側は処理を待つ。
use std::thread; use std::sync::mpsc; fn main() { let (tx, rx) = mpsc::channel(); for i in 0..10 { let tx = tx.clone(); thread::spawn(move || { let answer = i * i; tx.send(answer).unwrap(); }); } for _ in 0..10 { println!("{}", rx.recv().unwrap()); } let handle = thread::spawn(move || { panic!("oops!"); }); let result = handle.join(); assert!(result.is_err()); }
$ cargo run Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs Running `target/debug/5_6_concurrency` 0 1 4 16 25 9 64 36 81 49 thread '<unnamed>' panicked at 'oops!', src/main.rs:22 note: Run with `RUST_BACKTRACE=1` for a backtrace.
Concurrency
https://doc.rust-lang.org/book/concurrency.html
並列処理について。
use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; fn main() { let data = Arc::new(Mutex::new(vec![1, 2, 3])); for i in 0..3 { let data = data.clone(); thread::spawn(move || { let mut data = data.lock().unwrap(); data[0] += i; }); } thread::sleep(Duration::from_millis(50)); println!("{:?}", data); }
$ cargo run Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs Running `target/debug/5_6_concurrency` Mutex { data: [4, 2, 3] }
Iterators
https://doc.rust-lang.org/book/iterators.html
fn main() { let num = (1..) .filter(|&x| x % 2 == 0) .filter(|&x| x % 3 == 0) .take(5) .collect::<Vec<i32>>(); for n in num.iter() { println!("{}", n); } }
$ cargo run Finished debug [unoptimized + debuginfo] target(s) in 1.21 secs Running `target/debug/5_5_iterators` 6 12 18 24 30
関数型プログラミングでこういうの見かけますが、メソッド呼び出しを連結できるのは良いですね。
Documentation
https://doc.rust-lang.org/book/documentation.html
ソースコードに特殊なコメントを記載しておくと、ツールでドキュメント生成出来る。Java
のjavadoc
や、Python
等々サポートしている言語は多々ある有りますね。出自はクヌース先生の文芸的プログラミングですかね。
Conditional Compilation
https://doc.rust-lang.org/book/conditional-compilation.html
#[cfg]
にて色々設定できる。C言語でいう#if
、#ifdef
みたいなもののようです。
Testing
https://doc.rust-lang.org/book/testing.html
テストの実施環境について。言語に標準でテストの仕組みが含んでいたり、ドキュメントに記載されている。これだけでも今どきの言語だという感じがします。
テストの実施方法はドキュメントを読んだ限りではシンプル。assert_eq!
以外にもテスト用のマクロがあると思うので、実用となると色々と大変になるのでしょうが。
The Stack and the Heap
https://doc.rust-lang.org/book/the-stack-and-the-heap.html
スタックとヒープについて。 変数宣言でスタックが積み上がっていくなど、目新しいところはなさそう。