구조체, 열거형, 패턴 매칭
struct User { active: bool, username: String, email: String, sign_in_count: u64, }
let user = User { active: true, username: String::from("someusername123"), email: String::from("someone@example.com"), sign_in_count: 1, }; user.memail = String::from("anotheremail@example.com");
fn build_user(email: String, username: String) -> User { User { active: true, username, email, sign_in_count: 1, } }
let new_user = User { active: user.active, ..user };
struct Color(i32, i32, i32); struct Point(i32, i32, i32);
let black = Color(0, 0, 0); let origin = Point(0, 0, 0);
struct AlwaysEqual;
let subject = AlwaysEqual;
[derive(Debug)] struct Rectangle { width: u32, height: u32, }
let rect = Rectangle {...}; println!("rect is {:?}", rect);
impl Rectangle { fn area(&self) -> u32 { self.width * self.height } }
impl Rectangle { fn width(&self) -> bool { self.width > 0 } }
impl Rectangle { fn can_hold(&self, other: &Rectangle) -> bool { self.width > other.width && self.height > other.height } }
impl Rectangle { fn square(size: u32) -> Self { Self { width: size, height: size, } } }
impl Rectangle { fn area(&self) -> u32 {...} } impl Rectangle { fn can_hold(&self, other: &Rectangle) -> bool {...} }
enum IpAddrKind { V4, V6, }
let four = IpAddrKind::V4; let six = IpAddrKind::V6;
struct IpAddr { kind: IpAddrKind, address: String, }
enum IpAddr { V4(String), V6(String), }
let home = IpAddr::V4(String::from("127.0.0.1")); let loopback = IpAddr::V6(String::from("::1"));
impl IpAddr { fn call(&self) { // 메서드 본문 } }
enum Option<T> { None, Some(T), }
let some_number = Some(5); let some_char = Some('e'); let absent_number: Option<i32> = None;
let x: i8 = 5; let y: Option<i8> = Some(5); let sum = x + y; // 컴파일 에러
enum Coin { Penny, Nickel, Dime, } fn value_in_cents(coin: Coin) -> u8 { match coin { Coin::Penny => 1, Coin::Nickel => { println!("Nickel Coin!!!"); 5 }, Coin::Dime => 10, } }
enum IpAddrKind { V4(String), V6(String), }
fn get_addr(&self) -> &String { let result = match self { IpAddrKind::V4(ip) => ip, IpAddrKind::V6(ip) => ip, }; result }
fn plus_one(x: Option<i32>) -> Option<i32> { match x { None => None, Some(i) => Some(i + 1), } } let five = Some(5); let six = plus_one(five); let none = plus_one(None);
// 아래의 코드는 컴파일 에러 발생 fn plus_one(x: Option<i32>) -> Option<i32> { match x { Some(i) => Some(i + 1), } }
match dice_roll { 3 => add_fancy_hat(), 7 => remove_fancy_hat(), other => move_player(other), // _ => move_player(other), }
let config_max = Some(3u8); if let Some(max) = config_max { println!("The maximum is configured to be {}", max); }