Ownership (Rust)
๋ฉ์๋์ self
, &self
, &mut self
self
- ํจ์๊ฐ ๊ฐ์ ์๋ชจํ๋ ๊ฒฝ์ฐ. ์ค๋์ญ์ ๋ฐ๋๋ค. (move)
&self
- ํจ์๊ฐ ๊ฐ์ ์ฝ๊ธฐ๋ง ํ๋ ๊ฒฝ์ฐ. ์ฐธ์กฐ๋ง ๋ฐ๋๋ค. (borrow)
&mut self
- ํจ์๊ฐ ๊ฐ์ ์๋ชจํ์ง ์๊ณ ๋ณ๊ฒฝํ๋ ๊ฒฝ์ฐ. ๊ฐ๋ณ์ฐธ์กฐ๋ฅผ ๋ฐ๋๋ค. (borrow)
ํจ์์์ ์ฐธ์กฐ ๋ฐํํ๊ธฐ
- ํจ์์์ ์ฐธ์กฐ๋ฅผ ๋ฐํํ๋ ค ํ๋ฉด ์คํจํ๋ค.
fn try_create<'a>() -> &'a String {
&String::new()
}
- ํจ์ ๋ด์์ ๋ง๋ ์์ ๊ฐ์ ์ค๋์ญ์ ํจ์๊ฐ ๊ฐ์ง๊ณ ์๊ธฐ ๋๋ฌธ์ด๋ค.
- ํจ์๊ฐ ๋๋ ๋ ์์ ๊ฐ์ ๋๋๋๊ณ , ๋ฉ๋ชจ๋ฆฌ์์ ์ฌ๋ผ์ง๋ค.
- ๋ฐ๋ผ์ ๋ฐํํ๋ ค๋ ์ฐธ์กฐ๋ ๋๊ธ๋ง ์ฐธ์กฐ(Dangling reference)๊ฐ ๋๋ค.
error[E0515]: cannot return reference to temporary value
--> src/lib.rs:2:5
|
2 | &String::new()
| ^-------------
| ||
| |temporary value created here
| returns a reference to data owned by the current function
- ํจ์ ๋ด์์ ๋ง๋ ์์ ๊ฐ์ ์ฐธ์กฐ๋ฅผ ๋ฐํํ๋ ๊ฒ์ ๋ถ๊ฐ๋ฅํ๋ค.
์ฐธ๊ณ ์๋ฃ
์ด ๋ฌธ์๋ฅผ ์ธ์ฉํ ๋ฌธ์