《Rust Programming Language》- EX - Cheatsheet

2023-03-09 19:06:42 浏览数 (1)

Structs

Classic Structs

代码语言:javascript复制
struct ColorClassicStruct {
    red: i32,
    green: i32,
    blue: i32,
}


let green = ColorClassicStruct {
    red: 0,
    green: 255,
    blue: 0,
};

assert_eq!(green.red, 0);
assert_eq!(green.green, 255);
assert_eq!(green.blue, 0);

Tuples

代码语言:javascript复制
struct ColorTupleStruct(i32, i32, i32);


let green = ColorTupleStruct(0, 255, 0);

assert_eq!(green.0, 0);
assert_eq!(green.1, 255);
assert_eq!(green.2, 0);

Unit-Like Struct

Unit-like Struct: No fields, no data stored, behave similarly to ()

代码语言:javascript复制
struct UnitLikeStruct;


let unit_like_struct = UnitLikeStruct;
let message = format!("{:?}s are fun!", unit_like_struct);

Patterns of methods arguments

  • fn get_char(data: String) takes the String by value, allowing you to modify the string data, but it will make a full copy of the string data, which can be expensive for large strings.
  • fn get_char(data: &String) takes a reference to a String, allowing you to access the string data, but not modify it.
  • fn get_char(mut data: &String) Wrong syntax - you cannot take a mutable reference to an immutable reference.
  • fn get_char(mut data: String) takes a mutable String, allowing you to modify the string data, but it will also make a full copy of the string data.

Syntax

Ownership

Mutable

fn get_char(data: &String)

Caller

No

fn get_char(mut data: &String)

N/A

N/A

fn get_char(data: String)

Transferred to Function

No

fn get_char(mut data: String)

Transferred to Function

Yes

Enum

代码语言:javascript复制
enum Message {
    Quit,
    Move(Point),
    Echo(String),
    ChangeColor((u8, u8, u8)),
}

fn triggerSpecificEvent(message: Message) {
    // TODO: create a match expression to process the different message variants
    match message {
        Message::ChangeColor((a, b, c)) => change_color((a, b, c)),
        Message::Echo(s) => echo(s),
        Message::Move(p) => move_position(p),
        Message::Quit => quit(),
    }
}

0 人点赞