Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- fn f(s: &str) {
- println!("{}", s);
- }
- //reads a line from a file in linux
- fn process_line(filename: &str) -> Result<String, std::io::Error> {
- let f = std::fs::File::open(filename)?;
- use std::io::BufReader;
- use std::io::prelude::*;
- let b = BufReader::new(f);
- b.lines().next().unwrap()
- }
- fn main() {
- //Block valued expressions
- println!("{}", {let x = 5 + 3; println!("got x"); x});
- //is you use the & before passing s to f(),
- //there is an automatic conversion from
- //String to str.
- let s: String = "hello".to_string();
- f(&s);
- //This is similar to ?: in C
- let _m: String = if false {String::new()} else {"hello".to_string()};
- //match statment
- let n = 3;
- let b = match n {
- 0 => "whee".to_string(),
- 3 => "woohoo".to_string(),
- n => n.to_string(), //this n is different than the n above
- //the n on the left is meant to be a "default" value
- };
- println!("{}", b);
- //match with option return
- let d = Some(4);
- let h = match d {
- Some(0) => "whee".to_string(),
- Some(3) => "woohoo".to_string(),
- Some(p) => p.to_string(), //p is similar to n above
- None => "nope".to_string(), //you have to have a None case with option returns in a match
- };
- println!("{}", h);
- println!(); //used as a spacer between outputs
- //this prints a vector backwards
- let mut v = vec![1, 2, 3];
- while let Some(g) = v.pop() {
- println!("{}", g);
- }
- //prints a line of a file in linux
- println!("{}", process_line("/etc/passwd").unwrap());
- //more match using a function return
- let filename = "/etc/passwd";
- match process_line(filename) {
- Ok(line) => println!("{}", line),
- Err(err) => eprintln!("{}: {:?}", filename, err),
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement