如何使用字符串成员创建 Rust 结构? [英] 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.
推荐答案
如果字符串必须归结构所有,那么您应该使用 String
.或者,您可以使用具有静态生命周期(即程序的生命周期)的 &str
.例如:
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:
struct Foo {
bar: String,
baz: &'static str,
}
fn main() {
let foo = Foo {
bar: "bar".to_string(),
baz: "baz",
};
println!("{}, {}", foo.bar, foo.baz);
}
如果字符串的生命周期未知,那么你可以用生命周期参数化<code>Foo:
If the lifetime of the string is unknown, then you can parameterize Foo
with a lifetime:
struct Foo<'a> {
baz: &'a str,
}
另见:
如果您不确定字符串是否会被拥有(用于避免分配),那么您可以使用 borrow::Cow
:
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<'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);
}
请注意,Cow
类型是在整个生命周期内参数化的.生命周期指的是 borrowed 字符串的生命周期(即,当它是 Borrowed
时).如果你有一个 Cow
,那么你可以使用 borrow
并得到一个 &'a str
,你可以用它进行正常的字符串操作,而无需担心是否分配一个新字符串.通常,由于取消引用强制,不需要显式调用 borrow
.即,Cow
值将自动取消引用它们的借用形式,因此 &*val
其中 val
的类型为 Cow<'a,str>
将产生一个 &str
.
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<'a, str>
will produce a &str
.
这篇关于如何使用字符串成员创建 Rust 结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!