Rust 中字串到 STR 的轉換

Muhammad Adil 2023年1月30日 Rust Rust String
  1. Rust 中字串的概念
  2. Rust 中 str 的概念
  3. Rust 中字串到 str 的轉換
  4. Rust 中 str 和 String 的區別
Rust 中字串到 STR 的轉換

Rust 是一種被設計為健壯和安全的語言。它還關注從系統程式設計到指令碼編寫的任何事物的效能。

Rust 中的 String 型別不是不可變的,但 String 型別確實具有建立和操作字串的方法。本文將詳細討論 String&static str

Rust 中字串的概念

String 是一個包含向量 Vec 的結構,它是一個可以擴充套件的 8 位無符號陣列。

str 不同,String 擁有資料的所有權。因此,在將字串的值分配給變數時,不必使用 & 或借用狀態。

在初始化期間,String 的大小在編譯時可能是已知的或未知的,但它可以擴充套件直到其長度達到其限制。

語法:

let my_string = String::from("Hello World");

Rust 中 str 的概念

在 Rust 中,str 是定義字串文字的原始型別。它的資訊在程式二進位制檔案的記憶體位置中分配。

字串切片

切片是包含一系列專案並由語法表示的檢視。切片沒有所有權,但它們允許你參考專案出現的順序。

因此,字串切片是對字串元素序列的引用。

let hello_string = String::from("hello world");

let hello_slice = &hello_string[4.8];

字母 "hello world" 儲存在 hello_string 變數中。String 是一個可增長的陣列,包含每個字元的位置或索引。

字串文字

字串文字是通過將文字括在雙引號中來構造的。字串文字有點不同。

它們是字串切片,指的是作為可執行檔案的一部分儲存在只讀記憶體中的預分配文字。換句話說,RAM 是隨我們的軟體一起提供的,並且不依賴於堆疊快取。

Rust 中字串到 str 的轉換

字串可能在程式碼的整個生命週期中都不存在,這就是 &'static str 生命週期的含義,因此,你無法從它們中獲取 &'static str。只能從中獲取由 String 的生命週期指定的切片。

示例程式碼:

fn main() {
    let hello_string = String::from("Hello world");
    print_infi(&hello_string);
    print!("Adil {}", hello_string);
}
fn print_infi(infi: &str) {
    println!("Steve {} ", infi);
}

輸出:

Steve Hello world
Adil Hello world

執行程式碼

Rust 中 str 和 String 的區別

String Str
1. 可變的 不可變
2. 在編譯時,大小是未知的。 在編譯時,大小是已知的。
3. 資料儲存在堆中。 資料儲存在應用程式二進位制檔案的記憶體位置。
4. 要分配單個 str 變數,請使用或引用。 要分配字串變數值,你不需要使用或引用。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Muhammad Adil
Muhammad Adil avatar Muhammad Adil avatar

Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.

Facebook

相關文章 - Rust String