<Vec Part>
[예제 코드_1]
fn main() {
let names = vec![
String::from("John"),
String::from("Jane"),
];
do_something(names);
}
fn do_something(names: Vec<String>) {
println!("{:?}", names);
}
[실행 결과]
["John", "Jane"]
[예제 코드_2]
fn main() {
let names = vec![
String::from("John"),
String::from("Jane"),
];
do_something(names);
println!("{:?}", names);
}
fn do_something(names: Vec<String>) {
println!("{:?}", names);
}
[실행 결과]
error[E0382]: borrow of moved value: `names`
--> src/main.rs:7:22
[예제 코드_3]
fn main() {
let names = vec![
String::from("John"),
String::from("Jane"),
];
println!("{:?}", names);
do_something(names);
}
fn do_something(names: Vec<String>) {
println!("{:?}", names);
}
[실행 결과]
["John", "Jane"]
["John", "Jane"]
[예제 코드_4]
fn main() {
let names = vec![
String::from("John"),
String::from("Jane"),
];
do_something(&names);
println!("{:?}", names);
}
fn do_something(names: &[String]) {
println!("{:?}", names);
}
[실행 결과]
["John", "Jane"]
["John", "Jane"]
[예제 코드_5]
fn main() {
let names = vec![
String::from("John"),
String::from("Jane"),
];
do_something(names.clone());
println!("{:?}", names);
}
fn do_something(names: Vec<String>) {
println!("{:?}", names);
}
[실행 결과]
["John", "Jane"]
["John", "Jane"]
[예제 코드_6]
fn main() {
let names = vec![
String::from("John"),
String::from("Jane"),
];
let name: String = names[0];
println!("Hello, {}", name);
}
[실행 결과]
error[E0507]: cannot move out of index of `Vec<String>`
--> src/main.rs:6:24
[예제 코드_7]
fn main() {
let names = vec![
String::from("John"),
String::from("Jane"),
];
let name: &str = &names[0];
println!("Hello, {}", name);
}
[실행 결과]
Hello, John
[예제 코드_8]
fn main() {
let names = vec![
String::from("John"),
String::from("Jane"),
];
let name: &str =
names.get(0).unwrap();
println!("Hello, {}", name);
}
[실행 결과]
Hello, John
[예제 코드_9]
fn main() {
let names = vec![
String::from("John"),
String::from("Jane"),
];
let name: &str =
names.first().unwrap();
println!("Hello, {}", name);
}
[실행 결과]
Hello, John
[예제 코드_10]
fn main() {
let names = vec![
String::from("John"),
String::from("Jane"),
];
let mut names_iter =
names.into_iter();
let name: String =
names_iter.next().unwrap();
println!("Hello, {}", name);
}
[실행 결과]
Hello, John
[예제 코드_11]
fn main() {
let mut names = vec![
String::from("John"),
String::from("Jane"),
];
let name: String = names.pop()
.unwrap();
println!("Hello, {}", name);
}
[실행 결과]
Hello, Jane
<참조 1> https://itnext.io/rust-ownership-50-code-examples-96203fcf79ea
'Rust' 카테고리의 다른 글
[Rust] Deref(역참조) 예제 (36일차) (0) | 2023.01.19 |
---|---|
[Rust] Ownership(소유권) 기초 예제 : For Loop (35일차) (0) | 2023.01.18 |
[Rust] Ownership(소유권) 기초 예제 : Struct (33일차) (0) | 2023.01.15 |
[Rust] Ownership(소유권) 기초 예제 : i32 (32일차) (0) | 2023.01.14 |
댓글