[rust-dev] Use of moved variable

Michael Neumann mneumann at ntecs.de
Thu Dec 20 18:19:33 PST 2012


When I try to compile this program, I get a "Use of moved variable" error.

   fn fun(b: ~[u8]) {
     // ...

   fn main() {
     let bytes: ~[u8] = ~[1,2,3];

     loop { fun(bytes); }

t.rs:8:13: 8:18 error: use of moved variable: `bytes`
t.rs:8   loop { fun(bytes); }
I can avoid the problem, by rewriting the program towards this:

   fn fun(b: ~[u8]) -> ~[u8] { b }

   fn main() {
     let mut bytes: ~[u8] = ~[1,2,3];

     loop {
       bytes = fun(bytes);

I find this somehow very unintuitive, but of course I understand that 
the variable "has to move back".
Of course I can rewrite function "fun" to use &[u8] as parameter, but I 
want to call TcpSocket.write, which only accepts
a ~ [u8] and I don't know how to convert a &[u8] into a ~[u8]. As & can 
point to managed boxes I don't think it's possible
to convert safely.

So is there another "nice" solution to the problem? Maybe I am missing 



More information about the Rust-dev mailing list