如何在Rust的函数中返回str的错误

时间:2019-09-02 15:04:27

标签: rust

我是Rust的新手,几周前,我试图做Rust编写的东西,但是很长时间以来,编译错误就使我失望了。我想在函数中返回错误,现在我无法修复,我丢失了什么吗?

os:Mac 货运1.37.0(9edd08916 2019-08-02) rustc 1.37.0(eae3437df 2019-08-13)

use std::result::Result;
use serde_json;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
pub struct Sound {
  pub name: String,
}

pub fn get_sound() -> Result<Sound, &'static str> {

  let data = r#"
  {
    "name": "John Doe"
  }"#;

  let s: Sound = match serde_json::from_str(data) {
    Ok(val) => val,
    Err(err) => return Err(&format!("Parsing JSON error: {:?}", err)),
  };

  Ok(s)
}

error[E0515]: cannot return value referencing temporary value
  --> src/a.rs:19:24
   |
19 |     Err(err) => return Err(&format!("Parsing JSON error: {:?}", err)),
   |                        ^^^^^----------------------------------------^
   |                        |    |
   |                        |    temporary value created here
   |                        returns a value referencing data owned by the current function

0 个答案:

没有答案