๋ฌธ์์ด
Rust has two types to represent strings, both of which will be covered in more depth later. Both always store UTF-8 encoded strings.
String
- a modifiable, owned string.&str
- ์ฝ๊ธฐ ์ ์ฉ ๋ฌธ์์ด์ ๋๋ค. ๋ฌธ์์ด ๋ฆฌํฐ๋ด์ ์ด ํ์ ์ ๊ฐ์ง๋๋ค.
fn main() { let greeting: &str = " ์ธ์ฌ๋ง"; let planet: &str = "๐ช"; let mut sentence = String::new(); sentence.push_str(greeting); sentence.push_str(", "); sentence.push_str(planet); println!("๋ง์ง๋ง ๋ฌธ์ฅ: {}", sentence); println!("{:?}", &sentence[0..5]); //println!("{:?}", &sentence[12..13]); }
์ด ์ฌ๋ผ์ด๋๋ ๋ฌธ์์ด์ ์๊ฐํฉ๋๋ค. ์ฌ๊ธฐ์ ์๋ ๋ชจ๋ ๋ด์ฉ์ ๋์ค์ ์์ธํ ๋ค๋ฃจ๊ฒ ์ง๋ง ํ์ ์ฌ๋ผ์ด๋์ ์ฐ์ต๋ฌธ์ ์์ ๋ฌธ์์ด์ ์ฌ์ฉํ๋ ๋ฐ๋ ์ด๊ฒ์ผ๋ก ์ถฉ๋ถํฉ๋๋ค.
-
๋ฌธ์์ด ๋ด์ ์๋ชป๋ UTF-8 ์ธ์ฝ๋ฉ์ด ์๋ ๊ฒ์ ์ ์๋์ง ์์ ๋์์ด๋ฉฐ, ์ด๋ ์์ ํ Rust์์๋ ํ์ฉ๋์ง ์์ต๋๋ค.
-
String
์ ์์ฑ์(::new()
) ๋ฐs.push_str(..)
๊ณผ ๊ฐ์ ๋ฉ์๋๊ฐ ํฌํจ๋ ์ฌ์ฉ์ ์ ์ ํ์ ์ ๋๋ค. -
&str
์&
๋ ์ฐธ์กฐ์์ ๋ํ๋ ๋๋ค. ์ฐธ์กฐ๋ ๋์ค์ ๋ค๋ฃจ๋ฏ๋ก ์ง๊ธ์&str
์ โ์ฝ๊ธฐ ์ ์ฉ ๋ฌธ์์ดโ์ ์๋ฏธํ๋ ๋จ์๋ก ์๊ฐํ์ธ์. -
์ฃผ์ ์ฒ๋ฆฌ๋ ์ค์ ๋ฐ์ดํธ ์์น๋ณ๋ก ๋ฌธ์์ด์ ์์ธ์ ์์ฑํฉ๋๋ค.
12..13
์ ๋ฌธ์ ๊ฒฝ๊ณ์์ ๋๋์ง ์์ผ๋ฏ๋ก ํ๋ก๊ทธ๋จ์ด ํจ๋ ์ํ๊ฐ ๋ฉ๋๋ค. ์ค๋ฅ ๋ฉ์์ง์ ๋ฐ๋ผ ๋ฌธ์ ๊ฒฝ๊ณ์์ ๋๋๋ ๋ฒ์๋ก ์กฐ์ ํฉ๋๋ค. -
Raw strings allow you to create a
&str
value with escapes disabled:r"\n" == "\\n"
. You can embed double-quotes by using an equal amount of#
on either side of the quotes:fn main() { println!(r#"<a href="link.html">link</a>"#); println!("<a href=\"link.html\">link</a>"); }
-
Using
{:?}
is a convenient way to print array/vector/struct of values for debugging purposes, and itโs commonly used in code.