0

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();
}
2
  • 1
    doc["artifact_id"].as_str().map (String::from) should do what you want, although I would advise you to use serde_yaml to directly parse into a struct with the expected format. Commented Mar 4, 2024 at 14:59
  • Many thanks! Actually if there's the support for expected structss I will investigate serde_yaml. Commented Mar 4, 2024 at 15:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.