Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. #[derive(PartialEq)] //have to derive partial equal to compare two structs
  2. #[derive(Debug)]
  3.  
  4. struct Name {
  5. first: String,
  6. last: String,
  7. }
  8.  
  9. #[derive(Debug)]
  10. struct Point {
  11. x: i64,
  12. y: i64,
  13. }
  14.  
  15. //impl with a struct is how rust does classes (kind of)
  16. impl Point {
  17. fn new(x: i64, y: i64) -> Point {
  18. Point{x, y}
  19. }
  20.  
  21. fn flip(&mut self) {
  22. let tmp = self.x;
  23. self.x = self.y;
  24. self.y = tmp;
  25. }
  26.  
  27. fn flipped(&self) -> Point {
  28. Point{x: self. y, y: self. x}
  29. }
  30.  
  31. fn collapse(self) -> i64 {
  32. self.x + self.y
  33. }
  34. }
  35.  
  36. //enums in rust
  37. enum PointTwo {
  38. _PointTwo2{ _x: u64, _y: u64 },
  39. PointTwo3{ _x: u64, _y: u64, _z: u64},
  40. }
  41.  
  42. impl PointTwo {
  43. fn get_x(&self) -> u64 {
  44. match self {
  45. &PointTwo::_PointTwo2{ _x, ..} => _x,
  46. &PointTwo::PointTwo3{ _x, ..} => _x,
  47. }
  48. }
  49. }
  50.  
  51. fn main() {
  52. let first = "Paul".to_string();
  53. let last = "Hubbard".to_string();
  54. let s = Name{first, last}; //now first and last are owned by the struct
  55. // that is why we re-assign them below with the
  56. // values from the struct
  57. let first = &s.first;
  58. let last = &s.last;
  59. println!("{:?} {} {}", s, first, last);
  60.  
  61. //classes in rust (kind of)
  62. let mut p = Point::new(3,4);
  63. println!("{:?}", p.flipped().flipped());
  64. p.flip();
  65. println!("{:?}", p);
  66. println!("{}", p.collapse());
  67.  
  68. //enums with impl
  69. let en = PointTwo::PointTwo3{ _x:3, _y:2, _z:1 };
  70. println!("{}", en.get_x());
  71.  
  72. //you can say ' use Foo::* ' so you don't have to use identifiers
  73. //when setting variables (other then in the curly braces)
  74. use PointTwo::*;
  75.  
  76. let ne = _PointTwo2{_x:2, _y:3};
  77. println!("{}", ne.get_x());
  78.  
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement