1

I am trying to learn rust and got stuck at Ownership and Borrowing.

let s1 = String::from("Hello");
let s2 = s1;
print!("{}", s1); //---> Why this is an error ?

let a = "hello";
let b = a;
print!("{}", a); //--> But why this is not ?

Can someone kindly help me out on this ?

padmanabhanm
  • 315
  • 3
  • 15
  • 3
    TLDR: `String` is an owned type, so the ownership is transferred from `s1` to `s2` while `&str` is a reference type, so there is no ownership to be transferred. Or in other words, [reference types implement `Copy`](https://doc.rust-lang.org/std/primitive.reference.html#trait-implementations). – Boiethios Sep 16 '19 at 08:25
  • 1
    I'd say that a reference implements the Copy trait, while a String doesn't. The Copy trait is the real reason why there's no ownership transfer. – Denys Séguret Sep 16 '19 at 08:28

0 Answers0