gpt4 book ai didi

rust - 你如何设置 Rust 特性的生命周期?

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

我可以在结构 Route 中设置 Waypoint 的生命周期。在结构 AMoreDifferentRoute 中,我使用特征 Coord 并得到错误

explicit lifetime bound required

在这种情况下,您如何设置特征的生命周期?

extern crate collections;
use super::wp;
use coord::Coord;


pub struct Route<'a> {
waypoints: &'a Vec<wp::Waypoint>
}

pub struct AMoreDifferentRoute<'a> {
waypoints: &'a Vec<Coord>
}

最佳答案

你把它写成一个额外的特征界限:

pub struct AMoreDifferentRoute<'a> {   // '
waypoints: &'a Vec<Box<Coord+'a>>
}

您需要在 Box<Coord+'a> 中指定生命周期因为可以为本身具有生命周期参数的结构实现特征,所以即使实际结构类型隐藏在特征对象后面,也应该有一种方法来指定此生命周期参数。

而且,你不能有裸Coord因为它的大小未知,因为Vec需要知道它的组件大小才能将它们正确地放置在内存中。因此,您需要某种包装器来存储特征对象。 Box会做得很好。

关于rust - 你如何设置 Rust 特性的生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26327598/

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