본문 바로가기
Rust

[Rust] Ownership(소유권) 기초 예제 : String (31일차)

by 꾸압 2023. 1. 13.

 

<String Part>

[예제 코드_1]

fn main() {
    let name = String::from("Rust");
    do_something(name);
}

fn do_something(name: String) {
    println!("Hello, {}", name)
}

 

[출력 결과]

Hello, Rust!

 

[예제 코드_2]

fn main() {
    let name = String::from("Rust");
    do_something(name);
    println!("{}", name);
}

fn do_something(name: String) {
    println!("Hello, {}", name);
}

 

[출력 결과]

error[E0382]: borrow of moved value: `name`
 --> src/main.rs:4:20

 

[예제 코드_3]

fn main() {
    let name = String::from("Rust");
    let name_clone = name.clone();

    do_something(name);
    println!("{}", name_clone);
}

fn do_something(name: String) {
    println!("Name: {}", name);
}

 

[출력 결과]

Name: Rust!
Rust

 


 

[예제 코드_4]

fn main() {
    let name = String::from("Rust");
    do_something(&name);
    println!("{}", name);
}

fn do_something(name: &str) {
    println!("Hello, {}", name);
}

 

[출력 결과]

Hello, Rust!
Rust

 


 

[예제 코드_5]

fn main() {
    let name = String::from("Rust");
    println!("{}", name);
    do_something(name);
}

fn do_something(name: String) {
    println!("Hello, {}", name);
}

 

[출력 결과]

Rust
Hello, Rust!

 


 

<참조 1> https://itnext.io/rust-ownership-50-code-examples-96203fcf79ea

<참조 2>

 

 

댓글