軌道
/
Rust
Rust
/
課程大綱
/
字串切片
字串

字串切片 在 Rust

{other: "%{count} 個練習"}

關於 字串切片

Rust 實作字元陣列的方式有兩種:str 和 String。

str 又稱為「字串切片」,通常會搭配參考一起使用,寫成&str。

要了解原因,可以先看看為什麼下面這行程式碼無法編譯

const MY_CONST: str = *"Hello, World!";

// the size for values of type `str` cannot be known at compilation time
// the trait `Sized` is not implemented for `str`

雖然字面值 "Hello, World!" 的長度在編譯時就能知道,但就 str 而言,它是一段大小未知的序列。 但作為字面值的_參考_(&str),它會有一個「胖指標」,儲存該字面值在記憶體中的位址和長度。 胖指標的大小是已知的,所以這行程式碼可以編譯

const MY_CONST: &str = "Hello, World!";

字串切片的可變綁定可以替換它的值,但無法就地修改。

範例

let mut my_str = "Hello, World!";
my_str = "Hi!";
let mut my_string = String::from("Hello");
my_string.push_str(", World!"); // there is no equivalent function to modify &str

在定義函式的參數時,使用 &str 而非 &String 限制較少,因為下面這樣寫無法編譯

pub fn main() {
    let my_str: &str = "Hello, World!";
    say_hi(my_str);
}

fn say_hi(phrase: &String) {
    println!("{phrase:?}");
}

// mismatched types
// expected reference `&String`
// found reference `&str`

&str不會被強制轉型成&String。但這樣寫可以編譯

pub fn main() {
    let my_string = String::from("Hello, World!");
    say_hi(&my_string)
}

fn say_hi(phrase: &str) {
    println!("{phrase:?}");
}

&String會被強制轉型成&str。所以將參數型別設為&str通常會更有用。

透過 GitHub 編輯 連結會在新視窗或分頁中開啟