gpt4 book ai didi

rust - 函数调用在 Rust 中有生命周期,还是只有变量?

转载 作者:行者123 更新时间:2023-11-29 08:19:35 25 4
gpt4 key购买 nike

编辑:这个问题显然太复杂了。这是一个更简单的例子,它解释了我想问的问题:

#[feature(macro_rules)];    
macro_rules! trace(
($($arg:tt)*) => (
{ let x = ::std::io::stdout().write_line(format_args!(::std::fmt::format, $($arg)*)); println!("{}", x); }
);
)

#[deriving(Show)]
struct Foo<T> {
data: ~T
}

impl<T> Foo<T> {

// Notice how the 'pontless_marker' variable is passed into this function for
// no reason other than that it allows us to copy the lifetime scope of the
// 'marker' variable in the test below, so the lifetime of the returned pointer
// is valid for that block.
fn returns_to_scope_with_marker<'a>(&'a self, pointless_marker:&'a int) -> &'a ~T {
return &self.data;
}

// This doesn't work, but it should. You should be able to invoke this function
// as something like: let marked = bar.returns_to_scope::<LIFETIME???>();
/*
fn returns_to_scope<'a>(& self) -> &'a ~T {
return &self.data;
}
*/
}

#[test]
fn test_lifetime_return_scope() {
let bar = Foo { data: ~Foo { data: ~10 } };
{
let marker = 10;
let marked = bar.returns_to_scope_with_marker(&marker);
trace!("{:?}", marked);
}
}

参见上例中的“pointless_marker”。

这是我要避免的。如果该函数的类型也为 blah<'a>,我觉得我应该能够使用 x.blah:: () 显式调用它。

这完全不可能吗?

最佳答案

好的,这是有望解决您问题的代码:

#[feature(macro_rules)];    
//Macro rules is unchanged

#[deriving(Show)]
struct Foo<'a, T> {
data: &'a T
}

impl<'a, T> Foo<'a, T> {

fn returns_to_scope(&'a self) -> &'a T {
self.data
}
}

fn main() {
let bar = Foo { data: &Foo { data: &10 } };
{
let marked = bar.returns_to_scope();
trace!("{:?}", marked);
}
}

我将逐行(但不按顺序)解释问题是什么以及如何解决。

首先你说你想避免警告并避免发送无意义的变量。我同意这些参数是不必要的。为避免向函数及其参数添加变量,生命周期参数将添加到 impl。和 struct定义,在以下行中:

 struct Foo<'a, T> 
...
impl<'a, T> Foo<'a, T>
// note: impl<'a,T> is mandatory, because we can say <'a, int> for example
// which is not what we want

'a是一个生命周期参数,它充当另一种通用类型(即 T )。

*如果我们有'a终生我们有点需要将它与某些东西联系起来......我们将回到这部分一次fn returns_to_scope稍后在文本中修复,但很明显,数据将获得生命周期,因为它是结构 Foo 中的唯一值,并且它是从需要很多类似 &'a T 的函数返回的。 .

现在,我们可以更好地了解 fn returns_to_scope功能。如果您查看原始函数,您几乎是正确的。

 fn returns_to_scope<'a>(& self) -> &'a ~T {
return &self.data;
}

让我印象深刻的第一件事是你有一个 &~指针(&'a ~T)。为什么?您确实了解它是指向在堆上分配的指针的堆栈指针吗?除非你正在做一些指针指向杂技,否则它并不是很有用,但我认为这是一个错误。如果不好,您可以随时制作 ~T value并借用它。

所以你想要你的 returns_to_scope返回 self.data字段以某种方式返回,如果您要返回属于结构 Foo 的字段,我认为使用与该字段所属的结构 Foo 相同的生命周期更为明智;所以我将描述更改为:

fn returns_to_scope(&self) -> &'a T

我省略了 <'a>通用参数,因为我不需要将此函数概括为 'a生命周期,'a生命周期是结构的一部分,我们通过借用结构免费获得它。但是我忘了说 &self 上的哪个生命周期所以编译器会提示,我会改变 &self注释为 'a生命周期。

fn returns_to_scope(&'a self) -> &'a T

作为画龙点睛的一笔,因为 Rust 允许通过省略 ; 来返回字段我可以写:

fn returns_to_scope(&'a self) -> &'a T {
self.data
}

而不是 return self.data; .

现在我们看到结构中的字段是 'a 的自然候选者人生如此

data: &'a T

被添加到结构 Foo 中,现在所有部分都已就位。

关于rust - 函数调用在 Rust 中有生命周期,还是只有变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22358892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com