官术网_书友最值得收藏!

Impl blocks for enums

We can also provide implementations for enums. For example, consider a payments library built in Rust, which exposes a single API called pay:

// enum_methods.rs

enum PaymentMode {
Debit,
Credit,
Paypal
}

// Bunch of dummy payment handlers

fn pay_by_credit(amt: u64) {
println!("Processing credit payment of {}", amt);
}
fn pay_by_debit(amt: u64) {
println!("Processing debit payment of {}", amt);
}
fn paypal_redirect(amt: u64) {
println!("Redirecting to paypal for amount: {}", amt);
}

impl PaymentMode {
fn pay(&self, amount: u64) {
match self {
PaymentMode::Debit => pay_by_debit(amount),
PaymentMode::Credit => pay_by_credit(amount),
PaymentMode::Paypal => paypal_redirect(amount)
}
}
}

fn get_saved_payment_mode() -> PaymentMode {
PaymentMode::Debit
}

fn main() {
let payment_mode = get_saved_payment_mode();
payment_mode.pay(512);
}

The preceding code has a method called get_saved_payment_mode(), which returns a user's saved payment mode. This can either be a Credit Card, Debit Card, or Paypal. This is best modeled as an enum, where different payment methods can be added as its variants. The library then provides us with a single pay() method to which we can conveniently provide an amount to pay. This method determines which variant of the enum it is and dispatches methods accordingly to the correct payment service provider, without the library consumer worrying about checking which payment method to use.

Enums are also widely used for modeling state machines, and when combined with match statements, they make state transition code very concise to write. They are also used to model custom error types. When enum variants don't have any data associated with them, they can be used like C enums, where the variants implicitly have integer values starting with 0, but can also be manually tagged with integer (isize) values. This is useful when interacting with foreign C libraries.

主站蜘蛛池模板: 乌什县| 原阳县| 宁波市| 梅州市| 兴国县| 昭通市| 肥城市| 长子县| 新田县| 田东县| 芷江| 嵊泗县| 察隅县| 岑溪市| 大埔县| 林周县| 淮滨县| 理塘县| 麦盖提县| 鹤山市| 开平市| 四川省| 玛沁县| 桃江县| 西畴县| 孟村| 介休市| 镇平县| SHOW| 洛阳市| 色达县| 桐庐县| 普定县| 宁河县| 略阳县| 郎溪县| 沈阳市| 平乐县| 临湘市| 台安县| 新营市|