openlang

Why does this tuple move its string?

let message = String::from("hello");

let pair = (message, message.len());

// i'm puzzled about ownership passing b/w identical vars i.e the initial message and tuple message if every message is identical ,why does this work???

The conversation continues 2

Follow the reasoning
  1. Permalink

    Putting an existing variable into a tuple transfers that variable's ownership to the tuple. In addition, the order in which those things happen matters in some situations, and your example is one of them. Your example won't compile because the tuple takes the value before you access it again (the message.len() call happens after the move). However, write it this way instead:

    let message = String::from("hello");
    
    let pair = (message.len(), message);

    and compilation succeeds, since message.len() runs before the tuple takes ownership.

    I'd suggest going through the rustbook ownership chapter (https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html) as well, which should help make this clearer.

  2. Permalink

    and to preserve that order (message followed by length), introduce another variable and work out the lenght before you move message.

    let message = String::from("hello");
    
    let size = message.len();
    let pair = (message, size);

Other sides of the same question

  1. Same sink call, a copy on one line and a move on the next

    Nim 2 decides copy or move per call site. Not per proc. Same argument, same proc. The first call copies, because a is still n…

    Replies 2Latest activity nim
  2. Delaying a cleanup block's mutable borrow until it actually runs

    What would be a way for me to write a panic-safe mecanism in Rust that behaves similarly to Java's try { ... } finally { ...…

    Replies 2Latest activity rust
  3. Inputting character arrays through pointers

    Whenever I attempt keyboard input into some char arrays, my program ends up crashing. What's a straightforward way of reading…

    Replies 2Latest activity c