Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading