New rust user here.
I'm trying to use yaml_rust to parse my config files, and spotted a difficulty.
I am trying to keep Option<...> values to handle the possibility that a field is missing or null. Well, in yaml_rust you have these as_xxx accessors which look so handy, returning exactly that. Almost. There's as_str returning Option<&str>, but no as_string returning Option<String>.
So I concocted the following (preliminary lines as from yaml_rust usage example):
let yml_str = fs::read_to_string(file_name).unwrap();
let mut docs = YamlLoader::load_from_str(&yml_str).unwrap();
let doc = &docs[0];
let artifact_id =
if let Some(str) = doc["artifact_id"].as_str() {
Some(str.to_string())
} else {
None
};
Needless to say, it seems to me... verbose? Is it possibly the way to go?
Just to show what I tried: the into_xxx accessors do list a ``into_string() method)Option, but I spotted a (for me) obscure error. What is obscure is that the error seems related to doc["artifact_id"], but if I append doc["artifact_id"].as_str()the error vanishes, while when I appenddoc["artifact_id"].into string()``` it appears.
The following example shows the error.
use yaml_rust::YamlLoader;
fn main() {
let yml_str = "[]";
let docs = YamlLoader::load_from_str(&yml_str).unwrap();
let doc = &docs[0];
let _test = doc["artifact_id"].into_string();
}
The following one doesn't.
use yaml_rust::YamlLoader;
fn main() {
let yml_str = "[]";
let docs = YamlLoader::load_from_str(&yml_str).unwrap();
let doc = &docs[0];
let _test = doc["artifact_id"].as_str();
}
doc["artifact_id"].as_str().map (String::from)should do what you want, although I would advise you to useserde_yamlto directly parse into astructwith the expected format.structss I will investigate serde_yaml.