User Tools

Site Tools


Rust basic sample

Basic samples of

  • objects
  • closures
  • namespaces
  • directives
  • threads
basic.rs
#![allow(unused_variables)]
#![allow(unused_imports)]
 
use std::thread;
 
// object 
pub struct Package {
    size: i64
}
 
// object implementatation
impl Package {
    pub fn new(size: i64) -> Package {
        return Package { size: size };
    }
    pub fn getsize(&self) -> i64 {
        return self.size;
    }
    pub fn hello(&self) -> String {
        return String::from("object hello"); // create instanse of String
    }
}
 
// namespace sample 
mod some {
    pub fn hello() {
        println!("module hello");
    }
}
 
fn main() {
    // object usage sample
    let p = Package {size: 12};  // create instance 
    println!("{}", p.getsize()); // call implementation method
    println!("{}", p.hello());
 
    let n = Package::new(24);    // create instanse with fn new() 
    println!("{}", n.getsize()); // call method
 
    some::hello();  // call function from namespace some::
 
    let f = ||{ println!("closure hello"); };  // create closure
    f(); // call closure
 
    // create thread with closure 
    let t = thread::spawn(move ||{ println!("thread hello"); });
    let _ = t.join();
}

Out

$ rustc basic.rs
$ ./basic
12
object hello
24
module hello
closure hello
thread hello
$