why can't I write element to a moved position in array in Rust, but I can do it in tuple

I destruct an element from a tuple, and then write back a new element. It works.

  let mut a = ("111".to_string(), "222".to_string());
  let (b,_) = a;
  a.0 = "333".to_string();
  println!("{:?}", a);          //output:("333", "222")

But I can’t do it in an array:

    let mut a = ["111".to_string(), "222".to_string()];
    let [b,_] = a;
    a[0] = "333".to_string();
    ^^^^ value used here after partial move
    println!("{:?}", a);

I don’t why if a tuple is partial moved, I can use it again. But if an array is partial moved, I can’t use it anymore.

Could someone help me? Thanks a lot.

>Solution :

I don’t why if a tuple is partial moved, I can use it again. But if an array is partial moved, I can’t use it anymore.

Because a[0] = ... desugars to *IndexMut::index_mut(&mut a, 0) = ..., and that requires a to be "whole", because the compiler doesn’t peer through functions to see whether partially moved structures are OK (the compiler understands partial moves but they’re not part of the type system).

a.0 is setting a field on a struct, so the compiler understands the entire operation and that it "fills" the partially moved structure back to a valid one.

Note how if you remove the a.0 = "333".to_string(); statement you can’t print the tuple anymore, because it’s not complete anymore. However you can print a.1. Not so with the array, once you’ve partially moved it, a[1] is also invalid.

Leave a Reply