How to improve this snippet of code to get compile success?

I want to implement a function that return process::stdout value, I take Output as parameter

fn get_stdout(output: &Output) -> String {
    return (String::from_utf8(output.stdout)).unwrap();
// error in `output.stdout` 

cannot move out of output.stdout which is behind a shared reference
move occurs because output.stdout has type Vec<u8>, which does not implement the Copy trait

You take not Output, but &Output - that's the important distinction, since you can't steal the data from behind the reference. If you intend to reuse Output after call to get_stdout, you have to clone the standard output data, i.e. use String::from_utf8(output.stdout.clone()); otherwise, just change the argument to be Output directly.

I don't understand that I have used a borrowed Output, I should be granted to access all methods/properties, why still need to clone

You can access properties, but you can't move out of them. The Vec<u8> stored in output.stdout must remain unchanged after the call to your function. So, to have your own copy of the data inside it, you have to create that copy explicitly.

Here you try to take stdout from Output (i.e. try to take the ownership of stdout), but because you don't own output (you have a non-mutable reference) and the type of stdout (Vec<u8>) don't implement Copy you cannot do that.

So, you have two options:

  • borrow the value, i.e. take a non-mutable reference to the field : &output.stdout
  • clone the data to obtain a owned version : output.stdout.clone()
1 Like

The point is that when you write output.stdout in the way you're doing here, you are performing a move which destroys the original value. You only have a reference, so you're not allowed to destroy output.stdout.

1 Like

I believe the function you call, String::from_utf8, takes ownership of it's argument. You are sending in a reference to something you do not own.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.