String

String์€ ํž™์— ํ• ๋‹น๋˜๊ณ  ๊ฐ€๋ณ€ ๊ธธ์ด์˜ ํ‘œ์ค€ UTF-8 ๋ฌธ์ž์—ด ๋ฒ„ํผ์ž…๋‹ˆ๋‹ค:

fn main() {
    let mut s1 = String::new();
    s1.push_str("์•ˆ๋…•ํ•˜์„ธ์š”");
    println!("s1: len = {}, ์šฉ๋Ÿ‰ = {}", s1.len(), s1.capacity());

    let mut s2 = String::with_capacity(s1.len() + 1);
    s2.push_str(&s1);
    s2.push('!');
    println!("s2: len = {}, ์šฉ๋Ÿ‰ = {}", s2.len(), s2.capacity());

    let s3 = String::from("๐Ÿ‡จ๐Ÿ‡ญ");
    println!("s3: len = {}, ๋ฌธ์ž ์ˆ˜ = {}", s3.len(), s3.chars().count());
}

String์€ Deref<Target = str>์„ ๊ตฌํ˜„ํ•ฉ๋‹ˆ๋‹ค. ์ด๋Š” , String ๊ฐ’์— ๋Œ€ํ•ด์„œ๋„ str์˜ ๋ชจ๋“  ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœ ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์˜๋ฏธ ์ž…๋‹ˆ๋‹ค.

This slide should take about 10 minutes.
  • String::new๋Š” ์ƒˆ๋กœ์šด ๋นˆ ๋ฌธ์ž์—ด์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. String::with_capacity๋Š” ์ƒˆ๋กœ ๋งŒ๋“ค ๋ฌธ์ž์—ด ๋ฒ„ํผ์— ๋„ฃ์„ ๋ฐ์ดํ„ฐ ํฌ๊ธฐ๋ฅผ ์•Œ๊ณ  ์žˆ๋Š” ๊ฒฝ์šฐ์— ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
  • String::len์€ String์˜ ๋ฐ”์ดํŠธ ํฌ๊ธฐ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. (์‹ค์ œ ๋ฌธ์ž ๊ฐœ์ˆ˜์™€๋Š” ๋‹ค๋ฅผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.)
  • String::chars๋Š” ์‹ค์ œ ๋ฌธ์ž(character)๋“ค์— ๋Œ€ํ•œ ์ดํ„ฐ๋ ˆ์ดํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. char๋กœ ํ‘œํ˜„๋˜๋Š” ๋ฌธ์ž๋Š” ์šฐ๋ฆฌ๊ฐ€ ์‹ค์ œ๋กœ ์ธ์‹ํ•˜๊ณ  ์‚ฌ์šฉํ•˜๋Š” ๋ฌธ์ž์™€๋Š” ๋‹ค๋ฅผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ž์†Œ ๊ฒฐํ•ฉ์œผ๋กœ ๋ฌธ์ž๋ฅผ ํ‘œํ˜„ํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค. ์ด์— ๋Œ€ํ•ด์„œ๋Š” Grapheme Cluster๋ฅผ ์ฐธ๊ณ ํ•˜์„ธ์š”.
  • ์‚ฌ๋žŒ๋“ค์ด ๋ฌธ์ž์—ด์ด๋ผ๊ณ  ๋งํ•  ๋•Œ์—๋Š” &str์ด๊ฑฐ๋‚˜ String์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
  • ์–ด๋–ค ํƒ€์ž…์ด Deref<Target = T>๋ฅผ ๊ตฌํ˜„ํ•˜๊ณ  ์žˆ์œผ๋ฉด, ์ปดํŒŒ์ผ๋Ÿฌ๋Š” ์—ฌ๋Ÿฌ๋ถ„์ด T์˜ ๋ฉ”์†Œ๋“œ๋“ค์„ ํ˜ธ์ถœํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋„์™€์ค๋‹ˆ๋‹ค.
    • Deref ํŠธ๋ ˆ์ž‡์— ๊ด€ํ•ด์„œ ์•„์ง ๋‹ค๋ฃจ์ง€ ์•Š์•˜์œผ๋ฏ€๋กœ ์ด ์‹œ์ ์—์„œ๋Š” ์ด๊ฒƒ์œผ๋กœ ๋ฌธ์„œ์˜ ์‚ฌ์ด๋“œ๋ฐ” ๊ตฌ์กฐ๊ฐ€ ๋Œ€๋ถ€๋ถ„ ์„ค๋ช…๋ฉ๋‹ˆ๋‹ค.
    • String์€ Deref<Target = str>์„ ๊ตฌํ˜„ํ•˜๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์— String์— ๋Œ€ํ•ด์„œ๋„ str ๋ฉ”์†Œ๋“œ๋“ค์„ ํ˜ธ์ถœํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
    • Write and compare let s3 = s1.deref(); and let s3 = &*s1;.
  • String์€ ๋ฐ”์ดํŠธ ๋ฒกํ„ฐ์˜ ๋ž˜ํผ๋กœ ๊ตฌํ˜„๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค. ๋ฒกํ„ฐ๊ฐ€ ์ง€์›ํ•˜๋Š” ์—ฌ๋Ÿฌ๊ฐ€์ง€ ์—ฐ์‚ฐ๋“ค์„ String๋„ ์ง€์›ํ•ฉ๋‹ˆ๋‹ค. ๋‹ค๋งŒ String์€ ๋ช‡๊ฐ€์ง€ ๋ณด์žฅ ๋‚ด์šฉ์ด ๋” ์žˆ์Šต๋‹ˆ๋‹ค.
  • String์„ ์ธ๋ฑ์Šค๋กœ ์ ‘๊ทผํ•˜๋Š” ๋ฐฉ๋ฒ•๋“ค์„ ๋น„๊ตํ•ด๋ณด์„ธ์š”:
    • s3.chars().nth(i).unwrap()๋ฅผ ์ด์šฉํ•˜์—ฌ ํ•œ ๋ฌธ์ž๋ฅผ ์„ ํƒํ•˜๋Š” ๊ฒฝ์šฐ, i๊ฐ’์ด ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚  ๋•Œ, ๋ฒ—์–ด๋‚˜์ง€ ์•Š์„ ๋•Œ ๋™์ž‘์„ ์„ค๋ช…ํ•˜์„ธ์š”.
    • s3[0..4]๋ฅผ ์ด์šฉํ•ด์„œ ๋ฌธ์ž์—ด์˜ ์ผ๋ถ€๋ฅผ ์„ ํƒํ•˜๋Š”๋ฐ, ์Šฌ๋ผ์ด์Šค๊ฐ€ ์œ ๋‹ˆ์ฝ”๋“œ ๋ฌธ์ž์—ด ๊ฒฝ๊ณ„์— ๋”ฑ ๋งž์ง€ ์•Š์„ ๊ฒฝ์šฐ ์–ด๋–ป๊ฒŒ ๋˜๋Š”์ง€ ์„ค๋ช…ํ•˜์„ธ์š”.
  • Many types can be converted to a string with the to_string method. This trait is automatically implemented for all types that implement Display, so anything that can be formatted can also be converted to a string.