1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| enum IpAddKind { V4, V6, } struct IpAddr { kind: IpAddKind, address: String, }; let i1 = IpAddr { kind: IpAddKind::V4, address: String::from("127.0.0.1"), }; let i2 = IpAddr { kind: IpAddKind::V6, address: String::from("::1"), }; enum IpAdd2 { V4(String), V6(String), }; let i1 = IpAdd2::V4(String::from("127.0.0.1")); let i2 = IpAdd2::V6(String::from("::1")); enum IpAddr3 { V4(u8,u8,u8,u8), V6(String), }; let i1 = IpAddr3::V4(127,0,0,1); let i2 = IpAddr3::V6("String::from("::1)"); //4.经典用法 enum Message { Quit, Move{x: i32,y: i32}, //move是一个结构体 Write(String), Change(i32,i32,i32), }; //等同于 //struct QuitMessage; //类单元结构体 //struct MoveMessage { // x: i32, // y: i32, // } // struct WriteMessage(String) //struct Change(i32,i32,i32) //5.枚举类型的方法和match impl Message { fn prin(&self) { match *self { //解引用 Message::Quit => println!("Quit"), Message::Move{x,y} => println!("Move x = {},y = {}",x,y), Message::Change(a,b,c) => println!("Change a = {}, b = {},c = {}",a,b,c), _ => println!("Write") //此处会报错,因为这是一个引用,而真正想要的是string类型 //Message::Write(&s) => println!("Write = {}",s) } } } fn main() { let quit = Messag::Quit; quit.prin(); let mo = Messag::Move {x: 10 , y: 20}; mo.prin(); let wri = Message::Write(String::from("Hello")); wri.prin(); let change = Message::Change(1,2,3); change.prin(); }
|