[英]How to create a Rust struct with string members?
I want the members to be owned by the struct. 我希望成员归结构所有。 Sorry for the simple question, but I wasn't able to find an example. 很抱歉这个简单的问题,但我无法找到一个例子。 I'm looking for the correct declaration of a struct and instantiation examples. 我正在寻找结构和实例化示例的正确声明。
If the string has to be owned by the struct, then you should use String
. 如果字符串必须由struct拥有,那么您应该使用String
。 Alternatively, you could use an &str
with a static lifetime (ie, the lifetime of the program). 或者,您可以使用具有静态生命周期的&str
(即程序的生命周期)。 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: 如果字符串的生命周期未知,那么您可以使用生命周期参数化Foo
:
struct Foo<'a> {
baz: &'a str,
}
See also: 也可以看看:
If you're not sure whether the string will be owned or not (useful for avoiding allocations), then you can use borrow::Cow
: 如果您不确定该字符串是否拥有(对于避免分配有用),那么您可以使用borrow::Cow
:
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);
}
Note that the Cow
type is parameterized over a lifetime. 请注意, Cow
类型在整个生命周期中进行参数化。 The lifetime refers to the lifetime of the borrowed string (ie, when it is a Borrowed
). 生命周期是指借来的字符串的生命周期(即,当它是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. 如果你有一个Cow
,那么你可以使用borrow
并获得一个&'a str
,你可以用它来进行正常的字符串操作,而不必担心是否分配新的字符串。 Typically, explicit calling of borrow
isn't required because of deref coercions. 通常,由于deref强制,不需要明确调用borrow
。 Namely, Cow
values will dereference to their borrowed form automatically, so &*val
where val
has type Cow<'a, str>
will produce a &str
. 也就是说, Cow
值将自动取消引用它们的借用形式,因此&*val
其中val
具有类型Cow<'a, str>
将产生&str
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.