트랙
/
Rust
Rust
/
학습 과정
/
문자열 슬라이스
문자

문자열 슬라이스 에서 Rust

{other: "%{count}개의 연습 문제"}

문자열 슬라이스 소개

Rust가 문자 배열을 구현하는 방법에는 두 가지가 있어요: str과 String이에요.

str은 "문자열 슬라이스"라고도 하는데, 보통 &str처럼 참조와 함께 사용해요.

그 이유를 알려면 다음 코드가 왜 컴파일되지 않는지 이해하는 게 도움이 돼요.

const MY_CONST: str = *"Hello, World!";

// the size for values of type `str` cannot be known at compilation time
// the trait `Sized` is not implemented for `str`

"Hello, World!" 리터럴은 컴파일 시점에 길이를 알 수 있지만, str로서는 크기를 알 수 없는 나열이에요. 하지만 리터럴에 대한 참조(&str)라면, 메모리에서 리터럴의 주소와 길이를 함께 담는 "팻 포인터"가 돼요. 팻 포인터는 크기가 정해져 있어서, 다음 줄은 컴파일돼요.

const MY_CONST: &str = "Hello, World!";

문자열 슬라이스에 대한 가변 바인딩은 값을 다른 값으로 바꿀 수는 있지만, 제자리에서 수정할 수는 없어요.

예시

let mut my_str = "Hello, World!";
my_str = "Hi!";
let mut my_string = String::from("Hello");
my_string.push_str(", World!"); // there is no equivalent function to modify &str

함수의 매개변수를 정의할 때 &String 대신 &str을 쓰면 제약이 더 적어요. 다음 코드는 컴파일되지 않거든요.

pub fn main() {
    let my_str: &str = "Hello, World!";
    say_hi(my_str);
}

fn say_hi(phrase: &String) {
    println!("{phrase:?}");
}

// mismatched types
// expected reference `&String`
// found reference `&str`

&str은 &String으로 강제 변환되지 않아요. 하지만 다음 코드는 컴파일돼요.

pub fn main() {
    let my_string = String::from("Hello, World!");
    say_hi(&my_string)
}

fn say_hi(phrase: &str) {
    println!("{phrase:?}");
}

&String은 &str로 강제 변환돼요. 그래서 매개변수 타입으로 &str을 쓰는 게 더 유용할 때가 많아요.

GitHub에서 편집 링크가 새 창이나 탭에서 열려요