string 如何使用字符串成员创建 Rust 结构?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25754863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a Rust struct with string members?
提问by vladimir
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.
我希望成员归结构所有。对不起,这个简单的问题,但我找不到一个例子。我正在寻找结构和实例化示例的正确声明。
回答by BurntSushi5
If the string has to be owned by the struct, then you should use String
. Alternatively, you could use an &str
with a static lifetime (i.e., the lifetime of the program). For example:
如果字符串必须归结构所有,那么您应该使用String
. 或者,您可以使用&str
具有静态生命周期(即程序的生命周期)的 。例如:
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. The lifetime refers to the lifetime of the borrowedstring (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<'a, str>
will produce a &str
.
请注意,该Cow
类型是在整个生命周期内参数化的。生命周期是指借用字符串的生命周期(即,当它是 a 时Borrowed
)。如果您有 a Cow
,那么您可以使用borrow
和获取 a &'a str
,您可以使用它进行正常的字符串操作,而无需担心是否分配新字符串。通常,borrow
由于 deref 强制,不需要显式调用 of 。即,Cow
值将自动取消引用其借用形式,因此&*val
where val
has typeCow<'a, str>
将产生一个&str
.