Skip to content

Instantly share code, notes, and snippets.

@hsnks100
Created October 5, 2021 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hsnks100/fb0443aea4d5d88e97fc936141cdb8bd to your computer and use it in GitHub Desktop.
Save hsnks100/fb0443aea4d5d88e97fc936141cdb8bd to your computer and use it in GitHub Desktop.
rust 소유권 개념 박살내기
fn main() {
f1();
f2();
f3();
f4();
f5();
} // 여기서 x는 스코프 밖으로 나가고, s도 그 후 나갑니다. 하지만 s는 이미 이동되었으므로,
// 별다른 일이 발생하지 않습니다.
fn f1() {
let mut s = 55;
s += 5;
println!("{}", s);
let s2 = s;
println!("{}", s); // 가능
}
fn f2() {
let mut s = String::from("hello");
s.push_str(", world!"); // push_str()은 해당 스트링 리터럴을 스트링에 붙여줍니다.
println!("{}", s);
let s2 = s;
// println!("{}", s); // 불가능
}
fn f3() {
let mut s = String::from("hello");
takes_ownership(s);
// println!("{}", s); // 불가능
}
fn f4() {
let mut s = String::from("hello");
takes_ownership2(&s);
println!("{}", s); // 가능
}
fn takes_ownership(some_string: String) { // some_string이 스코프 안으로 들어왔습니다.
println!("{}", some_string);
} // 여기서 some_string이 스코프 밖으로 벗어났고 `drop`이 호출됩니다. 메모리는
// 해제되었습니다.
// 편리한 takes_ownership2
fn takes_ownership2(some_string: &String) {
println!("{}", some_string);
}
fn f5() {
let mut s = String::from("hello world");
let word = first_word(&s);
let word2 = first_word("ksoo hi");
println!("the first word is: {}", word);
println!("the first word is: {}", word2);
}
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment