A YAML tag labels a value’s type. Use tag() to read the explicit tag on port: !!str 80, where !!str marks 80 as a string.
cargo add oneyamlRequires Rust 1.85 or later.
use oneyaml::Document; fn main() { let yaml = "port: !!str 80\n"; let doc = Document::parse(yaml) .expect("valid YAML"); let port = doc.get("port").expect("port"); let tag = port.tag().expect("resolved tag"); match tag { Some(tag) => println!("{tag}"), None => println!("No explicit tag"), } }
Unzip the example, then cargo run.
cargo run prints:
tag:yaml.org,2002:strAn untagged node gives Ok(None); a missing key is a separate None from get. tag() returns Err only if a tag fails to resolve, which Document::parse rules out before the expect on tag() runs.
Variations
To see the no-tag case, change the first statement inside main as shown below. The program prints No explicit tag.
let yaml = "port: 80\n";Related recipes
The short answer
Parse with Document::parse, look up the value with get, and call tag() on it. In this input the name is tag:yaml.org,2002:str, not the shorthand !!str. You don’t need a Rust struct to inspect it.
How do I read a YAML file in Rust and get a tag from it?
Save port: !!str 80 in config.yaml. Run from the directory that contains the file. Replace the let yaml and let doc statements with these lines; leave the lookup and the tag check unchanged:
let yaml = std::fs::read_to_string("config.yaml") .expect("read config.yaml"); let doc = Document::parse(&yaml).expect("valid YAML");
If port is absent, there’s no node to inspect; if it exists but has no explicit tag, you get a node and tag() returns Ok(None).
What does a YAML tag like !!str mean?
The string tag tells a YAML processor to treat the value as a string. tag() reads the explicit tag and expands its shorthand. That lets you compare the resolved name rather than checking whether the input happened to spell it !!str.
Reading a tag isn’t the same as asking what type the parser infers. port: "80" can be a string without an explicit !!str, so the tag lookup still returns None. Use this method when you care whether the author actually wrote a tag, not when you only need the value’s type.