Clone

値のコピーを作成したい場合は、Clone トレイトを使用できます。

fn say_hello(name: String) {
    println!("Hello {name}")
}

fn main() {
    let name = String::from("Alice");
    say_hello(name.clone());
    say_hello(name);
}
This slide should take about 2 minutes.
  • The idea of Clone is to make it easy to spot where heap allocations are occurring. Look for .clone() and a few others like vec! or Box::new.

  • 借用チェッカーが通らない場合に「とりあえずクローンを作成して切り抜けておいて」、あとからクローンのないコードへの最適化を試みるのもよくあることです。

  • clone generally performs a deep copy of the value, meaning that if you e.g. clone an array, all of the elements of the array are cloned as well.

  • The behavior for clone is user-defined, so it can perform custom cloning logic if needed.