[rust-dev] Use of moved variable

Eric Holk eric.holk at gmail.com
Thu Dec 20 18:40:16 PST 2012


You could use vec::from_slice [1] to convert a slice to a unique vector, although for really performance sensitive work this may not be desirable because it introduces an extra copy.

The better option is probably to see if it's possible to rewrite TcpSocket.write to use &[u8] instead. I'd be surprised if there are serious issues; it was probably just written that way before slices were in common usage.

-Eric

[1]: http://dl.rust-lang.org/doc/core/vec.html#function-from_slice 

On Dec 20, 2012, at 6:19 PM, Michael Neumann <mneumann at ntecs.de> wrote:

> Hi,
> 
> 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 something...
> 
> Best,
> 
>  Michael
> _______________________________________________
> Rust-dev mailing list
> Rust-dev at mozilla.org
> https://mail.mozilla.org/listinfo/rust-dev



More information about the Rust-dev mailing list