Skip to content

Instantly share code, notes, and snippets.

@hayajo
Last active July 13, 2016 08:40
Show Gist options
  • Save hayajo/32a57ae38c87bc3681a35b428d46cf03 to your computer and use it in GitHub Desktop.
Save hayajo/32a57ae38c87bc3681a35b428d46cf03 to your computer and use it in GitHub Desktop.
「Rustを30分で紹介する(訳)」のコードを1.9.0で書いてみるとこんな感じ?
use std::thread;
use std::sync::mpsc;
fn main() {
let numbers = [1, 2, 3];
let (tx, rx) = mpsc::channel();
tx.send(numbers).unwrap();
let handle = thread::spawn(move || {
let numbers = rx.recv().unwrap();
println!("{}", numbers[0]);
});
handle.join().unwrap();
}
use std::thread;
use std::sync::mpsc;
use std::sync::Arc;
fn main() {
let numbers = [1, 2, 3];
let numbers_arc = Arc::new(numbers);
let handles: Vec<_> = (0..numbers.len()).into_iter().map(|num| {
let (tx, rx) = mpsc::channel();
tx.send(numbers_arc.clone()).unwrap();
thread::spawn(move || {
let local_arc = rx.recv().unwrap();
println!("{}", (*local_arc)[num]);
})
}).collect();
for h in handles {
h.join().unwrap();
}
}
use std::thread;
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
fn main() {
let numbers = [1, 2, 3];
let numbers_arc = Arc::new(Mutex::new(numbers));
let handles: Vec<_> = (0..numbers.len()).into_iter().map(|num| {
let (tx, rx) = mpsc::channel();
tx.send(numbers_arc.clone()).unwrap();
thread::spawn(move || {
let local_arc = rx.recv().unwrap();
let mut task_numbers = local_arc.lock().unwrap();
(*task_numbers)[num] += 1;
println!("{}", (*task_numbers)[num]);
// println!("{:?}", *task_numbers);
})
}).collect();
for h in handles {
h.join().unwrap();
}
}
fn dangling() -> &i32 {
let i = 1234;
return &i;
}
fn add_one() -> i32 {
let num = dangling();
return *num + 1;
}
fn main() {
let num = add_one();
println!("{}", num);
}
fn dangling() -> Box<i32> {
let x = Box::new(1234);
return x;
}
fn add_one() -> i32 {
let num = dangling();
return *num + 1;
}
fn main() {
let num = add_one();
println!("{}", num);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment