ํ์(dangling) ์ฐธ์กฐ
์ด์ Rust์ ๋ ๊ฐ์ง ๋ฌธ์์ด ํ์
์ ์ดํดํ ์ ์์ต๋๋ค. &str
์ ๊ฑฐ์ &[char]
์ ๋น์ทํ์ง๋ง ๋ฐ์ดํฐ๊ฐ ๊ฐ๋ณ ๊ธธ์ด ์ธ์ฝ๋ฉ(UTF-8)์ผ๋ก ์ ์ฅ๋ฉ๋๋ค.
fn main() { let s1: &str = "World"; println!("s1: {s1}"); let mut s2: String = String::from("Hello "); println!("s2: {s2}"); s2.push_str(s1); println!("s2: {s2}"); let s3: &str = &s2[6..]; println!("s3: {s3}"); }
๋ฌ์คํธ ์ฉ์ด:
&str
์ ๋ฌธ์์ด ์ฌ๋ผ์ด์ค์ ๋ํ (๋ถ๋ณ) ์ฐธ์กฐ์ ๋๋ค.String
์ ๋ฌธ์์ด์ ๋ด์ ์ ์๋ ๋ฒํผ์ ๋๋ค.
-
&str
์ ๋ฌธ์์ด ์ฌ๋ผ์ด์ค์ ๋๋ค. ๋ฌธ์์ด ์ฌ๋ผ์ด์ค๋ UTF-8๋ก ์ธ์ฝ๋ฉ๋ ๋ฌธ์์ด ๋ฐ์ดํฐ๋ฅผ ์๋ฏธํฉ๋๋ค. ๋ฌธ์์ด ๋ฆฌํฐ๋ด("Hello"
)์ ํ๋ก๊ทธ๋จ ๋ฐ์ด๋๋ฆฌ์ ์ ์ฅ๋ฉ๋๋ค. -
๋ฌ์คํธ์
String
ํ์ ์ ์ค์ ๋ก๋ ๋ฌธ์์ด์ ์ด๋ฃจ๋ ๋ฐ์ดํธ์ ๋ํ ๋ฐฑํฐ(Vec<u8>
)์ ๋๋ค.Vec<T>
๊ฐT
๋ฅผ ์์ ํ๊ณ ์๋ฏ์ด,String
์ด ๊ฐ๋ฆฌํค๊ณ ์๋ ๋ฌธ์์ด์String
์ ์์ ์ ๋๋ค. -
As with many other types
String::from()
creates a string from a string literal;String::new()
creates a new empty string, to which string data can be added using thepush()
andpush_str()
methods. -
The
format!()
macro is a convenient way to generate an owned string from dynamic values. It accepts the same format specification asprintln!()
. -
You can borrow
&str
slices fromString
via&
and optionally range selection. If you select a byte range that is not aligned to character boundaries, the expression will panic. Thechars
iterator iterates over characters and is preferred over trying to get character boundaries right. -
For C++ programmers: think of
&str
asstd::string_view
from C++, but the one that always points to a valid string in memory. RustString
is a rough equivalent ofstd::string
from C++ (main difference: it can only contain UTF-8 encoded bytes and will never use a small-string optimization). -
Byte strings literals allow you to create a
&[u8]
value directly:fn main() { println!("{:?}", b"abc"); println!("{:?}", &[97, 98, 99]); }