-3

I don't know how convert Option<&T> to Option<T>. I'm using the reqwest crate. This is my code:

let body: Option<Body> = request.body();

But I get mismatched type error. How do I convert Option<&Body> to <Option<Body>>?

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
pyama
  • 7
  • 5
    your question doesn't contain a [mcve], we can't answer you, but generally try to [`cloned()`](https://doc.rust-lang.org/std/option/enum.Option.html#method.cloned) – Stargateur Dec 25 '18 at 05:55
  • 3
    The question is why you want a `Option` at all? This seems either be a misunderstanding of ownership or a XY-Problem. – hellow Dec 25 '18 at 08:35
  • 2
    Possible duplicate of [How to convert Option<&T> to Option in the most idiomatic way in Rust?](https://stackoverflow.com/questions/51338579/how-to-convert-optiont-to-optiont-in-the-most-idiomatic-way-in-rust) – trent Dec 25 '18 at 11:39

1 Answers1

2

When you have an Option<&T>, you don't actually have the object itself. You have, maybe, a reference to the said object. Obviously, you cannot go from "a reference" to "a full-fledged owned object" without some trickery in between. You only currently have a pointer to the object, not the object itself, and as such, your only recourse is to find a way to make a copy of it.

If T implements Clone, you could in theory clone() your object and call it a day - this would turn your Option<&T> into Option<T> at the cost of a full memory copy. Judging by the type signature, this is probably a hyper question, however, and Body does not implement such a trait.

All other solutions will fail:

  • You cannot create a method on the object to destructure it and return self, as that would invalidate the borrow you have on &T
  • You have no way to turn directly from &T to T as you only have a borrow
Sébastien Renauld
  • 19,203
  • 2
  • 46
  • 66