rustで所有権ぽいやつをコードで追ってみる
所有権の説明
- 本家を読むと出てくる
- 以下の3つのルールが気になる訳です
Each value in Rust has a variable that’s called its owner. There can only be one owner at a time. When the owner goes out of scope, the value will be dropped.
- 所有権という変数を保持しているという話になる
- それぽいやつをコードを追うときに見てるので
- 追ってみる
実行
簡単なプログラムを起動する
1 fn main() { 2 let mut s = String::from("hello"); 3 s.push_str(", world"); 4 println!("{}",s); 5 }
String::fromへstepin
- 早速
to_owned
というメソッドが出てきています。
2228 impl From<&str> for String { 2229 #[inline] 2230 fn from(s: &str) -> String { 2231 s.to_owned() 2232 } 2233 }
- このメソッドは以下です
Some types make it possible to go from borrowed to owned, usually by implementing the Clone trait. But Clone works only for going from &T to T. The ToOwned trait generalizes Clone to construct owned data from any borrow of a given type. Creates owned data from borrowed data, usually by cloning.
- 内容的には特定の借用のときに使うぽい
202 #[stable(feature = "rust1", since = "1.0.0")] 203 impl ToOwned for str { 204 type Owned = String; 205 #[inline] 206 fn to_owned(&self) -> String { 207 unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) } 208 } 209 210 fn clone_into(&self, target: &mut String) { 211 let mut b = mem::take(target).into_bytes(); 212 self.as_bytes().clone_into(&mut b); 213 *target = unsafe { String::from_utf8_unchecked(b) } 214 } 215 }
- このケースは明示的に書く必要があるんだろうな。
- 後でまた戻ってくる。