From 445ed8498e695e04d83ca45623cc269f5b59c5b7 Mon Sep 17 00:00:00 2001 From: Librazy Date: Mon, 9 May 2016 19:34:48 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E5=AF=B9=E4=BA=8EString?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E7=9A=84=E6=8F=8F=E8=BF=B0=E5=B9=B6=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0from=5Futf8=E7=A4=BA=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- type/string.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/type/string.md b/type/string.md index 926a3b5..b31f3ac 100644 --- a/type/string.md +++ b/type/string.md @@ -5,7 +5,7 @@ 刚刚学习Rust的同学可能会被Rust的字符串搞混掉,比如`str`,`String`, `OsStr`, `CStr`,`CString`等等…… 事实上,如果你不做FFI的话,常用的字符串类型就只有前两种。我们就来着重研究一下Rust的前两种字符串。 -你要明白的是,Rust中的字符串实际上是被编码成UTF-8的一个Unicode字符数组。这么说比较拗口,简单来说,Rust字符串内部存储的是一个UTF-8数组,但是这个数组是Unicode字符经过编码得来的。因此,可以看成Rust原生就支持Unicode字符集(Python2的码农泪流满面)。 +你要明白的是,Rust中的字符串实际上是被编码成UTF-8的一个字节数组。这么说比较拗口,简单来说,Rust字符串内部存储的是一个u8数组,但是这个数组是Unicode字符经过UTF-8编码得来的。因此,可以看成Rust原生就支持Unicode字符集(Python2的码农泪流满面)。 ## str @@ -65,6 +65,17 @@ fn main() { 需要知道的是,将`String`转换成`&str`是非常轻松的几乎没有任何开销的。但是反过来,将`&str`转换成`String`是需要在堆上请求内存的,因此,要慎重。 +我们还可以将一个UTF-8编码的字节数组转换成String,如 +```rust +// 存储在Vec里的一些字节 +let miao = vec![229,150,181]; + +// 我们知道这些字节是合法的UTF-8编码字符串,所以直接unwarp() +let meow = String::from_utf8(sparkle_heart).unwrap(); + +assert_eq!("喵", meow); +``` + ## 索引访问 有人会把Rust中的字符串和其惯用的字符串等同起来,于是就出现了如下代码 From b98b2462b333a7517603f8c79501dc37b960c777 Mon Sep 17 00:00:00 2001 From: Librazy Date: Mon, 9 May 2016 23:50:26 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E4=B8=80=E7=82=B9=E5=BE=AE=E5=B0=8F?= =?UTF-8?q?=E7=9A=84=E5=96=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- type/string.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/type/string.md b/type/string.md index b31f3ac..435a881 100644 --- a/type/string.md +++ b/type/string.md @@ -71,7 +71,7 @@ fn main() { let miao = vec![229,150,181]; // 我们知道这些字节是合法的UTF-8编码字符串,所以直接unwarp() -let meow = String::from_utf8(sparkle_heart).unwrap(); +let meow = String::from_utf8(miao).unwrap(); assert_eq!("喵", meow); ```