简体   繁体   中英

serde_json::from_str error where string from file

extern crate serde_json;

use serde_json::Value;

use std::fs::File;
use std::io::prelude::*;

fn main() {
    let filepath = "./map/test/anhui.txt";
    match File::open(filepath) {
        Err(why) => println!("Open file failed : {:?}", why.kind()),
        Ok(mut file) => {
            let mut content: String = String::new();
            file.read_to_string(&mut content);
            println!("{}", &mut content);
            serde_json::from_str(&mut content);
        }
    }
}

Error info:

error: unable to infer enough type information about `_`; type annotations or generic parameter binding required [--explain E0282]
  --> src/main.rs:16:17
   |>
16 |>                 serde_json::from_str(&mut content);
   |>                 ^^^^^^^^^^^^^^^^^^^^

To fix it, you need to tell the compiler what type you are expecting as the result of serde_json::from_str . So you can change the line

serde_json::from_str(&mut content);

to

serde_json::from_str::<Value>(&mut content);

The reason you need to specify the type is becasue serde_json::from_str is a generic function which needs a type to be instantiated to a concrete function. Usually rustc takes care of it, and infer the type you want to use, but in this case, there is not enough information to let compiler infer it for you because the type is only referred in the result of the function while the result is never used in the given code.

You may also want to use the result of the from_str expression, otherwise the function call does nothing. If you specify the type when using a let binding, the compiler will be able to infer the type, like this:

let result: Value = serde_json::from_str(&mut content);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM