String — 소유된 UTF-8 문자열
String — 소유된 UTF-8 문자열
String은 소유한(owned) UTF-8 문자열 타입이에요. 가변적이며, 연속된 메모리에 UTF-8 인코딩된 바이트를 저장해요.
출처: Rust 공식 문서
본문
pub struct String { /* private fields */ }
주요 메서드
pub const fn new() -> String
pub fn with_capacity(capacity: usize) -> String
pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error>
pub fn from_utf8_unchecked(bytes: Vec<u8>) -> String // unsafe
pub fn len(&self) -> usize
pub fn is_empty(&self) -> bool
pub fn capacity(&self) -> usize
pub fn push(&mut self, ch: char)
pub fn push_str(&mut self, string: &str)
pub fn as_str(&self) -> &str
pub fn as_bytes(&self) -> &[u8]
pub fn truncate(&mut self, new_len: usize)
pub fn pop(&mut self) -> Option<char>
pub fn clear(&mut self)
예시
let mut s = String::from("hello");
s.push_str(", world");
s.push('!');
assert_eq!(s, "hello, world!");
String은 Deref<Target=str>을 구현해 &str 메서드(len, chars, split 등)를 사용할 수 있어요. + 연산자와 format! 매크로로 문자열을 이어 붙일 수 있어요. str과 달리 소유권을 가지며 가변적이에요.