[英]How can we return a static reference to a variable we make in a function in rust?
struct Foo<'a>(&'a str);
impl<'a> Foo<'a> {
fn get(&self) -> &'static str {self.0}
}
fn main() {
let value: &str;
{
let foo = Foo("Test Value");
value = foo.get();
}
println!("{}", value);
}
In this test code, I need to get the value stored in foo but as str is not sized, I can't just copy it's value.在这个测试代码中,我需要获取存储在 foo 中的值,但由于 str 没有大小,我不能只复制它的值。 I even tried cloning the str.
我什至尝试克隆str。 In a real life scenario, I could just use String or make a wrapper or encapsulate it in a box and return it but is there no way I can return a static reference to a variable I create in a function?
在现实生活场景中,我可以只使用字符串或制作包装器或将其封装在一个盒子中并返回它,但我无法返回一个 static 对我在 function 中创建的变量的引用吗? If so, how does the as_str function work in rust?
如果是这样, as_str function 如何在 rust中工作?
----Edit---- - - 编辑 - -
In this example, Neither putting 'static before str in Foo nor returning value with lifetime 'a works.在此示例中,将 'static 放在 Foo 中的 str 之前或返回具有生命周期的值 'a 都不起作用。 What to do then?
那该怎么办?
struct Foo<'a>(&'a [i32]);
impl<'a> Foo<'a> {
fn get(&self) -> &'static [i32] {self.0}
}
fn main() {
let value: &[i32];
{
let test_value = [0, 1, 2, 3];
let foo = Foo(&test_value);
value = foo.get();
}
println!("{:?}", value);
}
You can do it like this:你可以这样做:
struct Foo<'a>(&'a str);
impl<'a> Foo<'a> {
fn get(&self) -> &'a str {self.0}
}
fn main() {
let value: &str;
{
let foo = Foo("Test Value");
value = foo.get();
}
println!("{}", value);
}
Or like this:或者像这样:
struct Foo(&'static str);
impl Foo {
fn get(&self) -> &'static str {self.0}
}
fn main() {
let value: &str;
{
let foo = Foo("Test Value");
value = foo.get();
}
println!("{}", value);
}
The reason your code doesn't compile is that you're declaring you are returning a reference with a (potentially) longer lifetime.您的代码无法编译的原因是您声明您正在返回一个具有(可能)更长生命周期的引用。 Compare the lifetime of
static
with that of a
( self.0
has a lifetime of a
).将
static
的生命周期与a
的生命周期进行比较( self.0
的生命周期为a
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.