作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
<分区>
我是 Rust 的生命周期概念的新手,无法全神贯注于一段特定的代码。我一直在使用 Rust 的 SDL 绑定(bind)及其 Texture/TextureCreator 类,问题基本上归结为以下方案:
struct Creator;
impl Creator {
fn create(&self) -> Creature {
Creature { creator: &self }
}
}
struct Creature<'a> {
creator: &'a Creator,
}
struct MyStruct<'a> {
creator: Creator,
creatures: Vec<Creature<'a>>,
}
impl<'a> MyStruct<'a> {
fn new() -> MyStruct<'a> {
MyStruct {
creatures: Vec::new(),
creator: Creator,
}
}
fn create(&mut self) {
let new_creature = self.creator.create();
self.creatures.push(new_creature);
}
}
fn main() {
let mut my_struct = MyStruct::new();
my_struct.create();
}
实际问题出在MyStruct::create
里面方法。如果我尝试编译上面的代码,我会得到:
error[E0495]: cannot infer an appropriate lifetime for autoref due to con
flicting requirements
--> src/main.rs:27:41
|
27 | let new_creature = self.creator.create();
| ^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 define
d on the method body at 26:5...
--> src/main.rs:26:5
|
26 | / fn create(&mut self) {
27 | | let new_creature = self.creator.create();
28 | | self.creatures.push(new_creature);
29 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:27:28
|
27 | let new_creature = self.creator.create();
| ^^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on t
he impl at 18:6...
--> src/main.rs:18:6
|
18 | impl<'a> MyStruct<'a> {
| ^^
= note: ...so that the expression is assignable:
expected Creature<'a>
found Creature<'_>
有趣的是,当我在 MyStruct::create
中注释掉这一行时:
self.creatures.push(new_creature);
它编译得很好。
我的假设是它会导致以下问题 - 新创建的 new_creature
引用了 creator
属于my_struct
.现在,如果new_creature
然后由 creatures
拥有向量,我真的不能在 my_struct
上调用任何方法借用自己作为 mut
因为那时会有:
creator
里面my_struct
my_struct
的可变引用在方法体内(因此到 my_struct.creator
)不过,这是我个人的看法。从编译器的角度来看,它是关于生命周期的,但不太明白。所以我有以下两个问题:
Vec<Creature>
在结构中?我是否应该确保不同时保留 Creator
和 Vec<Creature>
在同一结构中以避免上述问题?这段代码在 Java 中的等价物是什么?我放了一部分,我对 I/O 部分感兴趣: int fd = open(FILE_NAME, O_WRONLY); int ret = 0; if (fd =
我正在尝试将维度为 d1,d2,d3 的张量 M[a1,a2,a3] reshape 为维度为 d2, d1*d3 的矩阵 M[a2,a1*a3]。我试过 M.reshape(d2,d1*d3) 但是
我是一名优秀的程序员,十分优秀!