You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
#[derive(Debug)]enumE{Value1,Value2,Value3,}fnmain(){let e :E = E::Value1;letmut e2 = E::Value2;println!("{:?}", e2);
e2 = E::Value3;println!("{:?} {:?}", e, e2);}
Enums as tagged variants, construction, handling
#[derive(Debug)]enumE{Number(u64),Text(String),}fnmain(){let e :E = E::Number(12);letmut e2 = E::Text("abc".to_string());println!("{:?}", e2);
e2 = E::Number(13);println!("{:?} {:?}", e, e2);}
#[derive(Debug)]structA{a:String,}#[derive(Debug)]enumE{Tuple(u64,u64),Text(A),}useE::Tuple;useE::Text;fnmain(){let aa = A{a:"xyz".to_string()};println!("{}", aa.a);let e :E = Tuple(12,13);letmut e2 = Text(A{a:"abc".to_string()});println!("{:?}", e2);
e2 = E::Tuple(13,12);println!("{:?} {:?}", e, e2);}
Enum arguments
#[derive(Debug)]structA{a:String,}#[derive(Debug)]enumE{Tuple(u64,u64),Text(A),}useE::Tuple;useE::Text;fnf(e:E){println!("In f: {:?}", e);}fnmain(){let aa = A{a:"xyz".to_string()};println!("{}", aa.a);let e :E = Tuple(12,13);letmut e2 = Text(A{a:"abc".to_string()});println!("{:?}", e2);f(e2);
e2 = E::Tuple(13,12);println!("{:?} {:?}", e, e2);}
Matching
#[derive(Debug)]structA{a:String,}#[derive(Debug)]enumE{Tuple(u64,u64),Text(A),}useE::Tuple;useE::Text;fnf(e:E){match e {Tuple(x, y) => {println!("f got a tuple: x={}, y={}", x, y);},Text(a) => {println!("f got a text: a={:?}", a);},}}fnmain(){let aa = A{a:"xyz".to_string()};println!("{}", aa.a);let e :E = Tuple(12,13);letmut e2 = Text(A{a:"abc".to_string()});println!("{:?}", e2);f(e2);
e2 = E::Tuple(13,12);println!("{:?} {:?}", e, e2);f(e);}
Methods for enums
#[derive(Debug)]structA{a:String,}#[derive(Debug)]enumE{Tuple(u64,u64),Text(A),}useE::Tuple;useE::Text;implE{fnf(&self){matchself{Tuple(x, y) => {println!("f got a tuple: x={}, y={}", x, y);},Text(a) => {println!("f got a text: a={:?}", a);},}}}fnmain(){let aa = A{a:"xyz".to_string()};println!("{}", aa.a);let e :E = Tuple(12,13);letmut e2 = Text(A{a:"abc".to_string()});println!("{:?}", e2);
e2.f();
e2 = E::Tuple(13,12);println!("{:?} {:?}", e, e2);
e.f();}
Inline structs
#[derive(Debug)]enumE{Empty,Value(i64),Tuple(u64,u64),Person{name:String,first_name:String,age:u16},}fnmain(){let a = E::Empty;let b = E::Value(12);let c = E::Tuple(1,2);let d = E::Person{name:"Miller".to_string(),first_name:"Mike".to_string(),age:37};println!("{:?} {:?} {:?} {:?}", a, b, c, d);}