Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Rust超初心者が頑張って勉強するの巻き

ieiriyuki
January 16, 2019
310

 Rust超初心者が頑張って勉強するの巻き

ieiriyuki

January 16, 2019
Tweet

Transcript

  1. Borrow fn eat_box_i32(boxed_i32: Box<i32>) { println!("Destroying box that contains {}",

    boxed_i32); } fn borrow_i32(borrowed_i32: &i32) { println!("This int is: {}", borrowed_i32); } fn main() { let boxed_i32 = Box::new(5_i32); let stacked_i32 = 6_i32; borrow_i32(&boxed_i32); borrow_i32(&stacked_i32); { let _ref_to_i32: &i32 = &boxed_i32; eat_box_i32(boxed_i32); // Error ! } eat_box_i32(boxed_i32); } ここで借用しているためデータを破 棄するような操作はできない
  2. Bound <>で囲まれているところが、バウンドを指定している とはいえ、バウンドの価値はよくわかっていない... ジェネリクスがあるのは便利だってGo勉強している人が言ってた #[derive(Debug)] struct Ref<'a, T: 'a>(&'a T);

    // `Ref` contains a reference to a generic type `T` that has // an unknown lifetime `'a`. `T` is bounded such that any // *references* in `T` must outlive `'a`. Additionally, the lifetime // of `Ref` may not exceed `'a`.
  3. Traits Sheepというstructに対し て、Animalというトレイトを 実装しています よく使うメソッドの集合っ てことでしょうか? struct Sheep { naked:

    bool, name: &'static str } trait Animal { fn new(name: &'static str) -> Self; fn name(&self) -> &'static str; fn noise(&self) -> &'static str; fn talk(&self) { println!("{} says {}", self.name(), self.noise()); } } // ~~ skip ~~ // impl Animal for Sheep { fn new(name: &'static str) -> Sheep { Sheep { name: name, naked: false } } fn name(&self) -> &'static str { self.name } fn noise(&self) -> &'static str { if self.is_naked() { "baaaaah?" } else { "baaaaah!" } } fn talk(&self) { println!("{} pauses briefly... {}", self.name, self.noise()); } }