Lifetimes when Deserializing JSON within a FromForm

后端 未结 1 1969
迷失自我
迷失自我 2020-12-21 18:21

I\'m having trouble understanding the relationship between the lifetimes on this code. Basically, I have a Rocket API that receives some x-www-form-urlencoded d

相关标签:
1条回答
  • 2020-12-21 19:06

    This section of the Serde website covers Deserialize bounds in detail.


    There are two main ways to write Deserialize trait bounds, whether on an impl block or a function or anywhere else.

    • <'de, T> where T: Deserialize<'de>

      This means "T can be deserialized from some lifetime." The caller gets to decide what lifetime that is. Typically this is used when the caller also provides the data that is being deserialized from, for example in a function like serde_json::from_str. In that case the input data must also have lifetime 'de, for example it could be &'de str.

    • <T> where T: DeserializeOwned

      This means "T can be deserialized from any lifetime." The callee gets to decide what lifetime. Usually this is because the data that is being deserialized from is going to be thrown away before the function returns, so T must not be allowed to borrow from it. In your case the data is coming from URL-decoding some input, and the decoded data is thrown away after deserializing T. Another common use of this bound is functions that deserialize from an IO stream, such as serde_json::from_reader.

      To say it more technically, the DeserializeOwned trait is equivalent to the higher-rank trait bound for<'de> Deserialize<'de>. The only difference is DeserializeOwned is more intuitive to read. It means T owns all the data that gets deserialized.

    Replacing your T: Deserialize<'f> bound with T: DeserializeOwned correctly communicates that T is not allowed to borrow from the URL-decoded data because the URL-decoded data will not outlive T.

    0 讨论(0)
提交回复
热议问题