Hi all,
I'm struggling with &str
, struct
and borrow. I expected fn get_property
below to put all chars from parameter line
into struct Property
's members name
and value
. I ask myself: The str "Hallo"
/ "Hallo:World"
is there and owned by fn main
, so how can it disappear when fn get_property
sets up a struct?
As I got Cow-doc any Cow relates to data that does not have to be owned as long as it is present.
What am I missing? Pls don't be captain obvious and reply: all
Chris
use std::borrow::Cow;
struct Property<'b> {
name: Cow<'b, str>,
value: Cow<'b, str>,
}
fn get_property<'c>(line: &'c str) -> Option<Property<'c>> {
let mut buffer = String::with_capacity(line.len());
let mut name = String::with_capacity(line.len());
let mut value = String::with_capacity(line.len());
for c in line.chars() {
buffer.push(c);
if c == ':' {
name.push_str(buffer.as_str());
name.pop().unwrap();
buffer.clear();
}
println!("{}\t{}", c, buffer);
}
if name.is_empty() || value.is_empty() {
None
}
else {
// late push for further elaboration
value.push_str(buffer.as_str());
Some(Property{ name: name.into(), value: value.into() })
}
}
fn main() {
assert!(get_property("Hallo").is_none());
assert!(get_property("Hallo:World").is_some());
let p = get_property("Hallo:World").unwrap();
assert_eq!(p.name, "Hallo");
assert_eq!(p.value, "World");
}
Output:
H H
a Ha
l Hal
l Hall
o Hallo
H H
a Ha
l Hal
l Hall
o Hallo
:
W W
o Wo
r Wor
l Worl
d World
Errors:
Compiling playground v0.0.1 (/playground)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.53s
Running `target/debug/playground`
thread 'main' panicked at src/main.rs:33:5:
assertion failed: get_property("Hallo:World").is_some()
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace