gpt4 book ai didi

rust - 在结构中存储函数特征对象的生命周期不够长

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

我正在尝试将两个函数存储在这样的结构中:

struct Example<'a> {
func1: &'a Fn(f64) -> f64,
func2: &'a Fn(f64) -> f64,
}

impl<'a> Example<'a> {

fn new(f1: &'a Fn(f64) -> f64, f2: &'a Fn(f64) -> f64) -> Example<'a> {
Example {
func1: f1,
func2: f2,
}
}

fn test_func(self, x: f64, y: f64) -> f64 {
(self.func1)(x) + (self.func2)(y)
}
}


fn main() {
fn first(x: f64) -> f64 {
x
}
fn second(x: f64) -> f64 {
x
}
let test = Example::new(&first, &second);
test.test_func(1.0, 2.0);
}

Rust playground

生成以下错误:

borrowed value does not live long enough
let test = Example::new(&first, &second);
^~~~~
note: reference must be valid for the block suffix following statement 2 at 28:45...
let test = Example::new(&first, &second);
test.test_func(1.0, 2.0);
}
note: ...but borrowed value is only valid for the statement at 28:4
let test = Example::new(&first, &second);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
help: consider using a `let` binding to increase its lifetime
let test = Example::new(&first, &second);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: borrowed value does not live long enough
let test = Example::new(&first, &second);
^~~~~~
note: reference must be valid for the block suffix following statement 2 at 28:45...
let test = Example::new(&first, &second);
test.test_func(1.0, 2.0);
}
note: ...but borrowed value is only valid for the statement at 28:4
let test = Example::new(&first, &second);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
help: consider using a `let` binding to increase its lifetime
let test = Example::new(&first, &second);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我对这是一个生命周期问题感到困惑,因为函数和结构体在 main 中应该共享相同的生命周期。也对为什么编译器的建议似乎与我已有的建议相同感到困惑。

最佳答案

按照编译器的建议(考虑使用 let 绑定(bind)来增加其生命周期)允许代码编译:

fn main() {
fn first(x: f64) -> f64 {
x
}
fn second(x: f64) -> f64 {
x
}

let x = &first;
let y = &second;
let test = Example::new(x, y);

println!("{}", test.test_func(1.0, 2.0));
}

同样

let x = first;
let y = second;
let test = Example::new(&x, &y);

我相信(但不知道如何证明)问题是必须创建一些东西来将函数指针 (fn(f64) -> f64) 适配到特征对象中(&Fn(f64) -> f64)。但是,在 new 调用中创建它意味着它会在语句返回时立即被删除。

这类似于文字引用的情况,它有同样的错误:

struct Foo<'a>(&'a u8);

fn main() {
let f = Foo(&4);
println!("{}", f.0);
}

关于rust - 在结构中存储函数特征对象的生命周期不够长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38174188/

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