STRUCTURES AND TUPLE



 STRUCTURES AND TUPLE

  • Structure is a general way of grouping a variety of types into a single compund type.
  • struct User {
        active: bool,
        name: String,
        age: u64,
    }
  • The above block shows a basic structure which groups related data into a single compound type.
  • It can be used in the given below format:
  • 
    fn main() {
        let user1 = User {
            age: 19,
            name: String::from("someusername123"),
            active: true,
        };
        println!("{}", user1.age);
    }
    
  • If the parameter names and struct field names are same, we can directly use the fields like below:
  • fn build_user(email: String, username: String) -> User {
        User {
            email,
            username,
            active: true,
            sign_in_count: 1,
        }
    }
    
    fn main() {
        let user1 = build_user(
            String::from("someone@example.com"),
            String::from("someusername123"),
        );
    }
    
  • There is an easier way to create a struct from another struct:
  • fn main() {
    
        let user1 = User {
            email: String::from("someone@example.com"),
            username: String::from("someusername123"),
            active: true,
            sign_in_count: 1,
        };
    
        let user2 = User {
            email: String::from("another@example.com"),
            ..user1
        };
    }
    
  • As shown in the above code, you can add the fields that you want to add like normally, and the remaining fields can be filled in with the user1 data using ..user1.

TUPLES STRUCT

  • Rust also supports struct that look similar to tuples called tuple struct.
  • Tuple struct is similar to normal struct apart from not having a name assocaited with each field.
  • struct Color(i32, i32, i32);
    struct Point(i32, i32, i32);
    
    fn main() {
        let black = Color(0, 0, 0);
        let origin = Point(0, 0, 0);
        print("{Colour is {}", black.0);
    }
    
  • The above code shows how to create tuple struct and how to use it.
  • You can print the whole tuple in the terminal using a trait called debug:
  • #[derive(Debug)]
    struct Color(i32, i32, i32);
    fn main() {
        let black = Color(0, 0, 0);
        print("{Colour is {:?}", black.0);
    }
  • The output would be like given below:
  • Color(0,0,0)
  • You can add methods for the struct using given below codes:
  • struct Color(i32, i32, i32);
    impl Color{
    
       fn describe(&self){
         println!("{}, {} and {}", self.0, self.1, self.2);
       }
    
       fn twice(&self) -> Color{
         Color(self.0 * 2, self.1 * 2, self.2 * 2)
       }
    
       fn make_twice(&mut self){
         self.0 *= 2;
         self.1 *= 2;
         self.2 *= 2;
       }
    }
    fn main() {
        let black = Color(0, 0, 0);
    
    }
  • The keyword impl followed by the tuple struct is the structure for adding methods for the structure. 
  • You can add multiple impl for the same struct, for make your code more readable.
  • The above methods can be called using below piece of codes:
  • fn main() {
        let mut black = Color(0, 0, 0);
        
        // simple tuple struct method call
        black.describe();
       
        // method call with a return type
        let white: Point = black.twice();
        
        // to mutate the tuple struct
        black.make_twice();
          
        
    }
  • Assoicated functions: Associated functions don't take self as a paramter and they are not method as they don't have a instance of struct to work with.
  • Unlike normal methods, associated functions are called using  :: rather than . .
  • A good example would be String::from().
  • The code below show how to create an associated function for struct
  • struct Color(i32, i32, i32);
    impl Color{
    
       fn zero() -> Color{
         Color(0,0,0)
       }
    
    
    }
    fn main() {
        let black = Color(0, 0, 0);
        // instead of using the above code we can rewrite it using assocaited function
        let black = Color::zero()
    
    }

Comments