Skip to content

Instantly share code, notes, and snippets.

@bellbind
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bellbind/84b1d03fae801ddcaf21 to your computer and use it in GitHub Desktop.
Save bellbind/84b1d03fae801ddcaf21 to your computer and use it in GitHub Desktop.
[rust]fizzbuzz and note on rust memory model
// 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) ?
// 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() {...})
@bellbind
Copy link
Author

on rust 0.10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment