2 ms·
> import json > with open("config.json") as f: > contents = f.read() > config = json.loads(contents) translates to: extern crate serde_json as json;
by f1b37cc0 9y ago
> import json
> with open("config.json") as f:
> contents = f.read()
> config = json.loads(contents)
translates to:
extern crate serde_json as json;
fn read_json() -> Result<json::Value, Box<std::error::Error>> {
let file = std::fs::File::open("config.json")?;
let config = json::from_reader(&file)?;
Ok(config)
}
And
> import configparser
> config = ConfigParser()
> config.read("config.conf")
can be translated to:
extern crate config;
use config::{Config, File, FileFormat};
fn read_config() -> Result<Config, Box<std::error::Error>> {
let mut c = Config::new();
c.merge(File::new("config", FileFormat::Json))?;
Ok(c)
}
Difficult stuff indeed.
- stable-point 9y agoI think this highlights that while there are easy solutions to the problem the OP faced, they're difficult for a newcomer to discover. (I have been using Rust for a couple of months and I'd also have reached for serde and maybe serde_derive to solve the problem). Hopefully this is something the Libz Blitz[0] will solve with their Rust Cookbook[1]. (You could almost but not quite arrive at as simple a solution from chapters 1 and 2). [0] https://blog.rust-lang.org/2017/05/05/libz-blitz.html https://blog.rust-lang.org/2017/05/05/libz-blitz.html [1] https://brson.github.io/rust-cookbook/intro.html https://brson.github.io/rust-cookbook/intro.html
- leshow 9y agoThe curious thing is that OP linked to the error handling docs, and the solution with Box<Error> is right there.