Rust 기초
Rust Strings: String vs &str
Rust has two string types. Learn when to use each, and how to grow, search and split text.
배울 내용
- String and &str
- push_str and push
- contains, split, len
Two string types
&str
- a borrowed view
- fixed size
- "Hello"
String
- owns its text
- can grow
- String::from("Hello")
An owned string and a borrowed view
Rust has two main string types. &str is a view of text stored somewhere else, such as a literal in your code. String owns its text and can grow.
String::from copies the literal into a String that the program owns, so push_str and push can add to it. len counts bytes, not characters. split returns the parts between the separator, one at a time.
핵심 포인트
- &str borrows text stored somewhere else.
- String owns its text and can grow.
- len counts bytes, not characters.
실행 가능한 Rust 예제
Rust
main.rs
fn main() {
let greeting = "Hello"; // &str: a borrowed string slice
let mut message = String::from(greeting); // String: owned and growable
message.push_str(", Rust");
message.push('!');
println!("{message}");
println!("length: {}", message.len());
println!("upper: {}", message.to_uppercase());
println!("contains Rust: {}", message.contains("Rust"));
for word in message.split(", ") {
println!("{word}");
}
}
Hello, Rust!
length: 12
upper: HELLO, RUST!
contains Rust: true
Hello
Rust!연습
예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.
이 레슨을 마쳤나요?
학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.
진행 상황이 이 브라우저에 저장되어 있습니다 로그인하면 모든 기기에서 이어갈 수 있습니다.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
- 모음 개수 세기 주어진 텍스트에서 모음의 개수를 세세요. 쉬움
- Initials From a Name Build uppercase initials from a full name. 쉬움