簡體   English   中英

當使用將在函數末尾刪除的String調用時,如何返回serde_json :: from_str的結果?

[英]How to return the result of serde_json::from_str when called with a String that will be dropped at the end of the function?

我在函數內部有一個新分配的String ,我需要創建一個派生對象,該派生對象從該String中借用&str並返回給定的對象。

我知道我的代碼是錯誤的,因為String生存期就是函數的生存期,因此派生的對象將永遠不會由於懸掛引用而返回。

這里的慣用解決方案是什么? 我無法更改serde_json::from_str的簽名

#[inline]
pub fn get_object<'a, T>(json_data: &'a Value, path: &[&str]) -> Option<T>
    where T: serde::Deserialize<'a>
{
    let mut pointer_str = String::new();
    for entry in path.iter() {
        pointer_str = format!("{}/{}", pointer_str, entry);
    }

    let child = json_data.pointer(&pointer_str).unwrap().to_string();

    let result = serde_json::from_str(&child).ok();
    return result;
}

錯誤:

error: `child` does not live long enough
  --> src/lib.rs:88:40
   |
88 |     let result = serde_json::from_str(&child).ok();
   |                                        ^^^^^ does not live long enough
89 |     return result;
90 | }
   | - borrowed value only lives until here

慣用的解決方案是:

  • T實現DeserializeOwned
  • 有兩種方法:一種創建字符串,另一種進行反序列化,並確保反序列化的結果存儲的時間長於T

當然,前者要容易得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM