Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #[derive(PartialEq)] //have to derive partial equal to compare two structs
- #[derive(Debug)]
- struct Name {
- first: String,
- last: String,
- }
- #[derive(Debug)]
- struct Point {
- x: i64,
- y: i64,
- }
- //impl with a struct is how rust does classes (kind of)
- impl Point {
- fn new(x: i64, y: i64) -> Point {
- Point{x, y}
- }
- fn flip(&mut self) {
- let tmp = self.x;
- self.x = self.y;
- self.y = tmp;
- }
- fn flipped(&self) -> Point {
- Point{x: self. y, y: self. x}
- }
- fn collapse(self) -> i64 {
- self.x + self.y
- }
- }
- //enums in rust
- enum PointTwo {
- _PointTwo2{ _x: u64, _y: u64 },
- PointTwo3{ _x: u64, _y: u64, _z: u64},
- }
- impl PointTwo {
- fn get_x(&self) -> u64 {
- match self {
- &PointTwo::_PointTwo2{ _x, ..} => _x,
- &PointTwo::PointTwo3{ _x, ..} => _x,
- }
- }
- }
- fn main() {
- let first = "Paul".to_string();
- let last = "Hubbard".to_string();
- let s = Name{first, last}; //now first and last are owned by the struct
- // that is why we re-assign them below with the
- // values from the struct
- let first = &s.first;
- let last = &s.last;
- println!("{:?} {} {}", s, first, last);
- //classes in rust (kind of)
- let mut p = Point::new(3,4);
- println!("{:?}", p.flipped().flipped());
- p.flip();
- println!("{:?}", p);
- println!("{}", p.collapse());
- //enums with impl
- let en = PointTwo::PointTwo3{ _x:3, _y:2, _z:1 };
- println!("{}", en.get_x());
- //you can say ' use Foo::* ' so you don't have to use identifiers
- //when setting variables (other then in the curly braces)
- use PointTwo::*;
- let ne = _PointTwo2{_x:2, _y:3};
- println!("{}", ne.get_x());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement