rustlings

전지현·2024년 11월 11일
0

Rust

목록 보기
15/17

디버깅하며 공부해보기!
https://github.com/rust-lang/rustlings

// TODO: We sometimes encourage you to keep trying things on a given exercise
// even after you already figured it out. If you got everything working and feel
// ready for the next exercise, enter `n` in the terminal.
//
// The exercise file will be reloaded when you change one of the lines below!
// Try adding a new `println!` and check the updated output in the terminal.

fn main() {
    println!(r#"       Welcome to...                      "#);
    println!(r#"                 _   _ _                  "#);
    println!(r#"  _ __ _   _ ___| |_| (_)_ __   __ _ ___  "#);
    println!(r#" | '__| | | / __| __| | | '_ \ / _` / __| "#);
    println!(r#" | |  | |_| \__ \ |_| | | | | | (_| \__ \ "#);
    println!(r#" |_|   \__,_|___/\__|_|_|_| |_|\__, |___/ "#);
    println!(r#"                               |___/      "#);
    println!();
    println!("This exercise compiles successfully. The remaining exercises contain a compiler");
    println!("or logic error. The central concept behind Rustlings is to fix these errors and");
    println!("solve the exercises. Good luck!");
    println!();
    println!("The file of this exercise is `exercises/00_intro/intro1.rs`. Have a look!");
    println!("The current exercise path will be always shown under the progress bar.");
    println!("You can click on the path to open the exercise file in your editor.");
}



  • 폴더 내 특정 파일만 실행시키고 싶을 때
    cargo run --bin functions2
    cargo run --bin (실행시키고자 하는 파일명 .rs 제외)



문자열 String과 &str의 차이

String과 &str의 차이:

String: 힙에 저장된 소유권을 가진 가변 문자열 타입.
&str: 문자열 데이터에 대한 불변 참조로, 주로 정적 메모리(예: 문자열 리터럴)나 String의 슬라이스를 가리킴.


문자열 리터럴(&str)의 본질 정적(Static) 메모리 저장:

"blue"는 컴파일 타임에 고정된 문자열입니다. 이 문자열은 프로그램 실행 중 정적 메모리(static memory)에 저장됩니다.
문자열 리터럴은 프로그램 내에서 변경되지 않고, 이 데이터를 참조하는 슬라이스(&str)가 반환됩니다.
슬라이스(&str)의 의미:

&str은 문자열 데이터에 대한 참조 타입입니다.
예를 들어, "blue"는 실제 메모리에 저장된 데이터(바이트 배열)를 가리키는 참조일 뿐입니다.
String과의 차이:

String은 힙(heap)에 저장되는 소유권을 가진 타입입니다.
문자열 데이터를 복사하거나, 수정하거나, 동적으로 확장할 수 있습니다.
반면, &str은 불변(immutable)이고, 복사나 소유권 개념과 관련이 없습니다.
타입이 &str인 이유
Rust는 문자열 리터럴을 기본적으로 효율적으로 관리하기 위해 &str 타입을 사용합니다:

메모리 효율성:
문자열 리터럴은 정적 메모리에 저장되므로, 추가적인 힙 할당 없이 &str 참조만으로 접근할 수 있습니다.
불변성 보장:
컴파일 타임에 고정된 값이므로, 런타임에서 변경되지 않도록 불변성을 유지합니다.
String으로 변환하려면?
문자열 리터럴을 String으로 변환하려면 다음과 같은 방법을 사용할 수 있습니다:

.to_string() 메서드:
"blue".to_string()은 문자열 리터럴을 String 타입으로 변환합니다.
String::from 함수:
String::from("blue")는 동일한 결과를 반환합니다.

0개의 댓글