kind: capsule status: active visibility: private license: CC-BY-SA-4.0 summary: String은 heap-allocated 가변 소유 타입. &str은 UTF-8 바이트 시퀀스의 불변 뷰(slice). 함수 인자는 대부분 &str로 받는다. tags: - rust - string - memory - capsule
Rust String vs str (&str) Capsule
Summary#
Rust의 String은 Vec<u8>처럼 힙에 할당된 소유·가변 문자열. str은 동적 길이의 UTF-8 바이트 시퀀스 자체이고 크기가 컴파일 시점에 알려져 있지 않아 항상 참조 &str로 다룬다. 함수 인자는 &str, 반환·저장은 String이 관용.
Claim#
핵심 구분#
| 타입 | 소유 | 가변 | 저장 위치 | 표기 |
|---|---|---|---|---|
String |
소유 | 가변 | 힙 | let s = String::from("hi") |
&str |
빌림 | 불변 | 어디든 (정적/힙/스택 가리키는 뷰) | let s: &str = "hi" |
&mut str |
빌림 | 제한적 가변 (같은 UTF-8 바이트 수만) | 희귀 | — |
&str이 가리킬 수 있는 곳#
- 정적: 문자열 리터럴
"foo"는&'static str— 바이너리에 박혀 있음 - 힙(String 내부):
String은Deref<Target=str>—&my_string을&str로 자동 변환 - 스택 배열:
let arr: [u8; 3] = [b'h', b'i', 0]+std::str::from_utf8(&arr[..2])
관용#
fn greet(name: &str) { // 인자는 &str — String·&str·문자열리터럴 전부 받음
println!("hi {name}");
}
fn build() -> String { // 소유권을 넘겨야 하면 String
let mut s = String::from("hi");
s.push_str(" world");
s
}
변환#
String → &str:&my_string또는my_string.as_str()&str → String:s.to_string()/String::from(s)/s.to_owned()
Scope#
- Rust 2015/2018/2021 에디션 공통
OsString/&OsStr,CString/&CStr,PathBuf/&Path도 같은 소유/빌림 대응 쌍
Caveats#
&str은 UTF-8 보장 — 임의 바이트는&[u8]사용- 문자열 인덱싱
s[0]은 허용 안 됨 (UTF-8 codepoint 경계 모호).s.chars().nth(0)또는s.as_bytes()[0] String::new()vsString::with_capacity(n)— 반복 push는 capacity 미리 잡기
Source#
- Q: https://stackoverflow.com/q/24158114
- A: https://stackoverflow.com/a/24159933 — by huon
- License: CC BY-SA 4.0 (Stack Exchange)
- last_edit: 2024
- 조회일: 2026-04-19
Sagwan Revalidation 2026-04-19T00:40:29Z#
- verdict:
ok - note: Rust String/&str의 소유·빌림 구분, 관용 패턴, 변환 방법 모두 2021 에디션 기준 현재도 정확하며 outdated된 내용 없음.