Last active
August 29, 2015 14:02
-
-
Save bellbind/84b1d03fae801ddcaf21 to your computer and use it in GitHub Desktop.
[rust]fizzbuzz and note on rust memory model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// fizzbuzz on rust 0.11 | |
// rustc fizzbuzz.rs | |
// ./fizzbuzz | |
fn main() { | |
for i in range(1u, 101) { | |
// xxx! denotes xxx is defined as macro | |
println!("{}", fizzbuzz(i)); | |
} | |
} | |
// function def with param and resulttype | |
fn fizzbuzz(n: uint) -> String { | |
// pattern match and wild card _ | |
match (n % 5, n % 3) { | |
(0, 0) => "FizzBuzz".to_string(), | |
(0, _) => "Fizz".to_string(), | |
(_, 0) => "Buzz".to_string(), | |
_ => n.to_str() | |
} | |
} | |
// 0.11 changes from 0.10 | |
// - "~T" is removed use "Box<T>" | |
// - especially "~str" moves to "String" | |
// - box "xxx" moves to "xxx".to_string() | |
// - Where gone box(GC) ? |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// rustc fizzbuzz.rs | |
// ./fizzbuzz | |
fn main() { | |
// communication channel for tasks | |
let (sender, receiver) = channel(); | |
// run process as task with spawn(proc() ...) | |
spawn(proc() for i in range(1u, 101) { | |
sender.send(fizzbuzz(i)); | |
}); | |
// use receiver as an iterator instread of receiver.recv() | |
spawn(proc() for r in receiver.iter() { | |
println!("{}", r); | |
}); | |
} | |
// function def with param and resulttype | |
fn fizzbuzz(n: uint) -> ~str { | |
// pattern matching with wild card "_" | |
match (n % 5, n % 3) { | |
(0, 0) => box "FizzBuzz", | |
(0, _) => box "Fizz", | |
(_, 0) => box "Buzz", | |
_ => n.to_str() | |
} | |
} | |
// [note] rust memory model | |
// - The string type "str" is alias of "u8" array slice (== "[u8]") | |
// - As a variable type, str should be used as one of pointer types | |
// - Threre are 3 pointer types by management types of the pointed memory | |
// - &str: "borrowed" => no ownership (& args semantics as in C) | |
// - ~str: "owned" => hold (passed) an ownership (unique_ptr as in C++) | |
// - @str: "managed" => shared ownership (shared_ptr as in C++) | |
// - string literal with memory location | |
// - "abc": &'static str => global scope memory | |
// - ~"abc" or box "abc": ~str => box which owner exchangable | |
// (ownership transferred when each assignment to "owned" vars) | |
// - @"abc": @str => local heap (shared only in a "task") | |
// - task: concurrent process with (unshared) local heaps | |
// - create task: spawn(proc() {...}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
on rust 0.10