Rust (programming language): Difference between revisions

Content deleted Content added
add sentence to fill missing timegap
Ownership and references: rm example that isn't contributing much
Line 439:
}
original
}
</syntaxhighlight>
 
When user-defined types hold references to data, they also need to use lifetime parameters. The example below parses some configuration options from a string and creates a struct containing the options. The function <code>parse_config</code> also showcases lifetime elision, which reduces the need for explicitly defining lifetime parameters.{{sfn|Klabnik|Nichols|2019|pp=201–203}}
 
<syntaxhighlight lang="rust">
use std::collections::HashMap;
 
// This struct has one lifetime parameter, 'src. The name is only used within the struct's definition.
#[derive(Debug)]
struct Config<'src> {
hostname: &'src str,
username: &'src str,
}
 
// The '_ lifetime parameter, in this case, refers to the anonymous lifetime attached to the type
// of the argument `config`.
fn parse_config(config: &str) -> Config<'_> {
let key_values: HashMap<_, _> = config
.lines()
.filter(|line| !line.starts_with('#'))
.filter_map(|line| line.split_once('='))
.map(|(key, value)| (key.trim(), value.trim()))
.collect();
Config {
hostname: key_values["hostname"],
username: key_values["username"],
}
}
 
fn main() {
let config = parse_config(
r#"hostname = foobar
username=barfoo"#,
);
println!("Parsed config: {:#?}", config);
}
</syntaxhighlight>