Rust Note(4)_Data Type III [String]

Rust 字符串類型


在 Rust 裡面, 字符串類型分以下兩種:

  • &str : 字符串字面量
  • String : 公開的 struct

在這之前, 先來理解一個概念 指針

指針 : 在 C++裡面有一樣的概念
想成把方向指到一個記憶體位址, 也就是 Rust 裡面常常會看到有人說 borrow 借用的概念

借用 borrow


當一個變量被賦值成立, 也就代表被分配一個內存位址
當變數成立, 代表在記憶體中這個值是唯一, 不能去改變(除非設定為可變 mut), 不然只能唯讀.
那我們就是利用 & 符號來借用
可借用的有 :

  • Type : 型態
  • Value : 值 (可為字串/整數/福點數)

&str 字符串字面量


str : 大小未知, 只能在指針後使用

也就是一個位址, 要把指針指到str的地方, 套用str的型態

所以 str 都必須要與 & 一起使用.

範例 :

1
2
3
4
5
fn main() {
let a: &str = "Hello world";
println!("{}", a)
}
// output : Hello world

如果沒有與 & 連用

1
2
3
4
fn main() {
let a: str = "Hello world";
println!("{}", a)
}

輸出報錯:

1
2
3
4
5
6
7
8
9
10
11
12
13
error[E0277]: the size for values of type `str` cannot be known at compilation time
--> src\main.rs:3:5
|
3 | println!("{}", a)
| ^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
::: C:\Users\kylls\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib/rustlib/src/rust\library\core\src\fmt\mod.rs:294:20
|
294 | pub fn new<'b, T>(x: &'b T, f: fn(&T, &mut Formatter<'_>) -> Result) -> ArgumentV1<'b> {
| - required by this bound in `ArgumentV1::<'a>::new`
|
= help: the trait `Sized` is not implemented for `str`
= note: this error originates in the macro `$crate::format_args_nl` (in Nightly builds, run with -Z macro-backtrace for more info)

看看 compiler 跟我們說的

size 未知, 導致無法編譯

也就是說, 沒有指針指到一個明確的記憶體位址


String 字符串對象


OOP 物件導向編程
String 就是一個對象, 型態為字符串

透過以下方法建立

  • new
  • from

先看 new的部分:

  1. 直接 new 出一個記憶體空間(堆 heap) 來儲存
  2. 用 push_str 的方式, 從後段把字符添加上去

Example:

1
2
3
4
5
6
7
fn main() {
let mut a = String::new();
a.push_str("Hello world, you!");
println!("{}", a)
}

// output : Hello world, you!

再來看from的部分

  1. 直接將字符串寫進去
  2. 同時間 compiler 會同步把字符串 new 出一個新的堆來儲存.
1
2
3
4
5
fn main() {
let a = String::from("Hello you, world!");
println!("{}", a)
}
// output : Hello you, world!

new 單純是一個字符字面上的量, 而 from 出來的是一個字符串的對象


字串操作


如果要操作字串就必須要轉成字符串對象

  • to_string() : 轉換為字符串對象
  • replace(a, b) : a 為要取代的字符, b 為取代的字符 a 替換成 b
  • as_str() : 把字符對象轉為字符量 (from to new)
  • push() : 原字符串後面追加
  • push_str() : 功能同 push
  • len() : 獲得字符串長度
  • trim() : 去除字首字尾空白符號
  • spilit_whitespace() : 以空白符作為分開依據
  • split(“.”) : 以 . 為節點分開
  • char() : 將字串打散為單一字符

Rust_Note 20211023_1.1