如何指定自定义结构寿命

时间:2019-05-18 14:29:10

标签: rust

我有一个自定义结构来映射从标准输入中获取的JSON。函数从stdin读取JSON并返回Result<MyCustomStruct, Error>。我想在主要功能中使用该结构引用:

use serde::{Deserialize, Serialize};

use reqwest::Client;

use std::error::Error;
use std::io::Read;

#[derive(Deserialize, Debug)]
struct Bar {
    pub id: String,
    pub url: String,
}

#[derive(Deserialize, Debug)]
struct Foo {
    pub bar: Bar,
}

pub struct ApiClient {
    url: &'static str,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct RooStruct {
    pub resp: String,
}

fn get_item_by_id(base_url: &str, _id: &str) -> Result<RooStruct, Box<Error>> {
    let url = format!("{}{}{}", base_url, "/api/items/uid/", _id);
    let client = Client::new();
    let res: RooStruct = client.get(&url).send()?.json()?;

    Ok(res)
}

impl ApiClient {
    pub fn new(url: &'static str) -> ApiClient {
        ApiClient { url: url }
    }

    pub fn get_item_by_id(&mut self, _id: &str) -> Result<RooStruct, Box<Error>> {
        match get_item_by_id(self.url, _id) {
            Ok(res) => Ok(res),
            Err(e) => Err(e),
        }
    }
}

fn read_from_stdin() -> Result<Foo, Box<Error>> {
    let mut input_buffer = String::new();
    let stdin = std::io::stdin();
    let mut handle = stdin.lock();
    handle.read_to_string(&mut input_buffer)?;
    let input: Foo = serde_json::from_str(&input_buffer)?;

    Ok(input)
}

fn main() {
    let stdin_input = read_from_stdin();
    if stdin_input.is_err() {
        println!("Error! {:?}", stdin_input.unwrap_err());
        return;
    }
    let input = stdin_input.unwrap();

    let bar = input.bar;
    let id = bar.id;
    let url = bar.url;

    let mut client = ApiClient::new(&url);

    // get_item_by_id expect &str as a param
    match client.get_item_by_id(&id) {
        Ok(res) => println!("Item: {:#?}", res),
        Err(e) => println!("error fetching item: {:?}", e),
    }
}

playground

我希望获得结构体值引用,但出现此错误:

error[E0597]: `url` does not live long enough
  --> src/main.rs:71:37
   |
71 |     let mut client = ApiClient::new(&url);
   |                      ---------------^^^^-
   |                      |              |
   |                      |              borrowed value does not live long enough
   |                      argument requires that `url` is borrowed for `'static`
...
78 | }
   | - `url` dropped here while still borrowed```

我了解这意味着什么,但是我不确定如何正确实施生命周期。

0 个答案:

没有答案
相关问题