snippetrustCritical
How to create a Rust struct with string members?
Viewed 0 times
withstructhowrustmembersstringcreate
Problem
I want the members to be owned by the struct. I'm looking for the correct declaration of a struct and instantiation examples. I wasn't able to find an example.
Solution
If the string has to be owned by the struct, then you should use
If the lifetime of the string is unknown, then you can parameterize
See also:
If you're not sure whether the string will be owned or not (useful for avoiding allocations), then you can use
Note that the
String. Alternatively, you could use an &str with a static lifetime (i.e., the lifetime of the program). For example:struct Foo {
bar: String,
baz: &'static str,
}
fn main() {
let foo = Foo {
bar: "bar".to_string(),
baz: "baz",
};
println!("{}, {}", foo.bar, foo.baz);
}If the lifetime of the string is unknown, then you can parameterize
Foo with a lifetime:struct Foo {
baz: &'a str,
}See also:
- What are the differences between Rust's
Stringandstr?
If you're not sure whether the string will be owned or not (useful for avoiding allocations), then you can use
borrow::Cow:use std::borrow::Cow;
struct Foo {
baz: Cow,
}
fn main() {
let foo1 = Foo {
baz: Cow::Borrowed("baz"),
};
let foo2 = Foo {
baz: Cow::Owned("baz".to_string()),
};
println!("{}, {}", foo1.baz, foo2.baz);
}Note that the
Cow type is parameterized over a lifetime. The lifetime refers to the lifetime of the borrowed string (i.e., when it is a Borrowed). If you have a Cow, then you can use borrow and get a &'a str, with which you can do normal string operations without worrying about whether to allocate a new string or not. Typically, explicit calling of borrow isn't required because of deref coercions. Namely, Cow values will dereference to their borrowed form automatically, so &*val where val has type Cow will produce a &str.Code Snippets
struct Foo {
bar: String,
baz: &'static str,
}
fn main() {
let foo = Foo {
bar: "bar".to_string(),
baz: "baz",
};
println!("{}, {}", foo.bar, foo.baz);
}struct Foo<'a> {
baz: &'a str,
}use std::borrow::Cow;
struct Foo<'a> {
baz: Cow<'a, str>,
}
fn main() {
let foo1 = Foo {
baz: Cow::Borrowed("baz"),
};
let foo2 = Foo {
baz: Cow::Owned("baz".to_string()),
};
println!("{}, {}", foo1.baz, foo2.baz);
}Context
Stack Overflow Q#25754863, score: 172
Revisions (0)
No revisions yet.