Rust

RUST Documentation 따라 공부하기 10

2019.12.30


Enums and Pattern Matching

enumerations : enums - to define a type by enumerating its possible values

enum IpAddrKind {
  V4,
  V6
}

let four = IpAddrKind::V4;
let six = IpAddrKind::V6;

fn route(ip_kind: IpAddrKind) { }

route(IpAddrKind::V4);
route(IpAddrKind::V6);

위와 같은 형식으로 사용 가능

:: 을 사용하여 접근함.

struct IpAddr {
  kind: IpAddrKind,
  address: String,
}

let home = IpAddr {
  kind: IpAddrKind::V4,
  address: String::from("127.0.0.1"),
};

let loopback = IpAddr {
  kind: IpAddrKind::V6,
  address: String::from("::1"),
};

enum이 struct를 대체가능 할 수도 있음.

enum IpAddr {
  V4(String),
  V6(String),
}

let home IpAddr::V4(String::from("127.0.0.1"));
let home IpAddr::V6(String::from("::1"));

each variant can have different types and amounts of associated data.

enum IpAddr {
  V4(u8, u8, u8, u8),
  V6(String),
}

let home = IpAddr::V4(127,0,0,1);
let loopback = IpAddr::V6(String::from("::1"));

좋은 사용 방법

enum Message {
  Quit,
  Move { x: i32, y: i32},
  Write(String),
  ChangeColor(i32, i32, i32),
}

struct QuitMessage; // unit struct
struct MoveMessage {
  x: i32,
  y: i32,
}
struct WriteMessage(String); // tuple struct
struct ChangeColorMessage(i32, i32, i32);

impl Message {
  fn call(&self) {
    // method body would be defined here
  }
}

let m = Message::Write(String::from("hello"));
m.call();

Option enum

The problem with null values is that if you try to use a null value as a not-null value, you'll get an error of some kind. Rust does not have nulls, but it does have an enum that can encode the concept of a value being present or absent.

enum Option<T> {
  Some(T),
  None,
}
  • You don't need to bring it into scope explicitly
  • you can use Some and None directly without the Option:: prefix.
let some_number = Some(5);
let some_string = Some("a string");
let absent_number: Option<i32> = None;

Why is having Option<T> any better than having null?

let x: i8 = 5;
let y: Option<i8> = Some(5);
let sum = x+y; // error!!
// how to add i8 and Option<i8> ?

how do you get the T value out of a Some variant when you have a value of type Option<T> so you can use that value?