experiments

All kinds of coding experiments
Log | Files | Refs | Submodules

custom_types.rs (1618B)


      1 // Custom types
      2 //  struct   : structure
      3 //  enum     : enumeration
      4 
      5 // Structs
      6 //  Tuple structs   : Essentially named tuples, i.e. fields
      7 struct Tuple(i32, i32, i32, i32);
      8 //  Classic structs : Named fields, like C
      9 #[derive(Debug)]
     10 struct Classic {
     11     a_field: i32,
     12     b_field: String,
     13 }
     14 //  Unit structs    : Field-less, useful for generics
     15 struct Unit;
     16 
     17 enum Status {
     18     InSync,
     19     Syncing,
     20     Error,
     21 }
     22 
     23 enum StatusExplicit {
     24     InSync = 1,
     25     Syncing = 2,
     26     Error = 3,
     27 }
     28 
     29 impl Status {
     30     // Instance function
     31     fn print(&self, prefix: String) {
     32         let str_status = match self {
     33             Self::InSync => "all good",
     34             Self::Syncing => "working!",
     35             Self::Error => "oh no",
     36         };
     37         println!("{} {}", prefix, str_status);
     38     }
     39     // Like Java static function
     40     fn get_error() -> Status {
     41         return Status::Error;
     42     }
     43 }
     44 
     45 const STATUS_PREFIX: &str = "It's";
     46 
     47 fn main() {
     48     let c = Classic {
     49         a_field: 234,
     50         b_field: String::from("Some string"),
     51     };
     52     println!("{:?}", c);
     53     let t = Tuple(1, 3, 5, 7);
     54     println!("{:?}", t.1);
     55     let s = Status::Syncing;
     56     // Call .print on the instance
     57     s.print(String::from(STATUS_PREFIX));
     58     // `use`, like used here, makes the `Status::` prefix unnecessary.
     59     // Notice the wildcard to include all instead of individual fields
     60     use crate::Status::*;
     61     InSync.print(String::from("Now it's"));
     62     println!("Implicit discriminator: {}", InSync as i32);
     63     println!("Explicit: {}", StatusExplicit::InSync as i32);
     64     println!("Static function: {}", Status::get_error() as i32)
     65 }