如何使结构中的字段引用rust中主函数中的值?

如何使结构中的字段引用rust中主函数中的值?,rust,sfml,Rust,Sfml,我需要创建一个名为Ant的结构来存储的实例,要创建我需要引用的精灵,我将创建大约100个Ant实例,但每个实例中的精灵都需要相同的纹理。 这是我的密码- struct Ant, x:f32, y:f32, 方向:f32, 速度:f32, } 注入src/main.rs:18:43 | 18 |让精灵=精灵::带有|纹理(纹理); | ^^^^^^^ | 注意:首先,生命周期不能超过17:21在方法体上定义的匿名生

我需要创建一个名为
Ant
的结构来存储的实例,要创建我需要引用的精灵,我将创建大约100个Ant实例,但每个实例中的精灵都需要相同的纹理。
这是我的密码-

struct Ant,
x:f32,
y:f32,
方向:f32,
速度:f32,
}
注入src/main.rs:18:43
|
18 |让精灵=精灵::带有|纹理(纹理);
|                                           ^^^^^^^
|
注意:首先,生命周期不能超过17:21在方法体上定义的匿名生命周期。。。
-->src/main.rs:17:21
|
17 | fn新(纹理:&SfBox,x:f32,y:f32,方向:f32)->Self{
|                     ^^^^^^^^^^^^^^^
注意:…这样引用就不会超过借用的内容
-->src/main.rs:18:43
|
18 |让精灵=精灵::带有|纹理(纹理);
|                                           ^^^^^^^
注意:但是,该生存期必须在16:10对impl上定义的生存期“uuu”有效。。。
-->src/main.rs:16:10
|
16 |暗示`

发现'Ant每个
&
引用都有一个生存期;如果您不编写一个,编译器会为您选择它(省略的生存期)。当您编写

implant{
fn新(纹理:&'a SfBox,x:f32,y:f32,方向:f32)->Self{

这应该可以解决您当前的生存期问题。我不熟悉
sfml
,因此代码可能存在其他问题。

不要保留对同一个非复制值的多个引用,而是保留一个键(例如索引)它将在显示时用于访问纹理。要使其更干净,请记住,您可以为索引定义类型别名。您是否尝试通过
&'a texture
(而不是对框的引用)获取
纹理
,并使整个
实现
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
  --> src/main.rs:18:43
   |
18 |         let sprite = Sprite::with_texture(texture);
   |                                           ^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime defined on the method body at 17:21...
  --> src/main.rs:17:21
   |
17 |     fn new(texture: &SfBox<Texture>, x: f32, y: f32, direction: f32) -> Self {
   |                     ^^^^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:18:43
   |
18 |         let sprite = Sprite::with_texture(texture);
   |                                           ^^^^^^^
note: but, the lifetime must be valid for the lifetime `'_` as defined on the impl at 16:10...
  --> src/main.rs:16:10
   |
16 | impl Ant<'_> {
   |          ^^
note: ...so that the expression is assignable
  --> src/main.rs:19:9
   |
19 | /         Ant {
20 | |             sprite,
21 | |             x,
22 | |             y,
23 | |             direction,
24 | |             speed: 4.
25 | |         }
   | |_________^
   = note: expected `Ant<'_>`
              found `Ant<'_>`

error: aborting due to previous error