Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. fn f(s: &str) {
  2. println!("{}", s);
  3. }
  4.  
  5. //reads a line from a file in linux
  6. fn process_line(filename: &str) -> Result<String, std::io::Error> {
  7. let f = std::fs::File::open(filename)?;
  8. use std::io::BufReader;
  9. use std::io::prelude::*;
  10. let b = BufReader::new(f);
  11. b.lines().next().unwrap()
  12. }
  13.  
  14. fn main() {
  15. //Block valued expressions
  16. println!("{}", {let x = 5 + 3; println!("got x"); x});
  17.  
  18. //is you use the & before passing s to f(),
  19. //there is an automatic conversion from
  20. //String to str.
  21. let s: String = "hello".to_string();
  22. f(&s);
  23.  
  24. //This is similar to ?: in C
  25. let _m: String = if false {String::new()} else {"hello".to_string()};
  26.  
  27. //match statment
  28. let n = 3;
  29. let b = match n {
  30. 0 => "whee".to_string(),
  31. 3 => "woohoo".to_string(),
  32. n => n.to_string(), //this n is different than the n above
  33. //the n on the left is meant to be a "default" value
  34. };
  35.  
  36. println!("{}", b);
  37.  
  38. //match with option return
  39. let d = Some(4);
  40. let h = match d {
  41. Some(0) => "whee".to_string(),
  42. Some(3) => "woohoo".to_string(),
  43. Some(p) => p.to_string(), //p is similar to n above
  44. None => "nope".to_string(), //you have to have a None case with option returns in a match
  45. };
  46.  
  47. println!("{}", h);
  48. println!(); //used as a spacer between outputs
  49.  
  50. //this prints a vector backwards
  51. let mut v = vec![1, 2, 3];
  52. while let Some(g) = v.pop() {
  53. println!("{}", g);
  54. }
  55.  
  56. //prints a line of a file in linux
  57. println!("{}", process_line("/etc/passwd").unwrap());
  58.  
  59. //more match using a function return
  60. let filename = "/etc/passwd";
  61. match process_line(filename) {
  62. Ok(line) => println!("{}", line),
  63. Err(err) => eprintln!("{}: {:?}", filename, err),
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement