gpt4 book ai didi

rust - 特质默认方法中的多次 self 借用

转载 作者:行者123 更新时间:2023-12-03 11:30:28 27 4
gpt4 key购买 nike

我在借阅检查器上遇到了问题。我有一个特征(Physics),它具有getters(例如velocity)和setters(例如velocity_mut)。它还具有使用getter和setter的默认方法accelerateapply_force。为什么多次借贷不好,如何解决呢?这是一条错误消息:

       13:18    rustc           error       cannot borrow `*self` as immutable because it is also borrowed as mutable
immutable borrow occurs here
12:11 rustc hint mutable borrow occurs here
12:11 rustc hint argument requires that `*self` is borrowed for `'static`
use gdnative::prelude::*;

// Running into issues with the borrow checker

trait Physics {
fn apply_force(&mut self, force: &mut Vector2, truncate: bool) {
let max_force = self.max_force();

if force.square_length() > max_force * max_force && truncate {
*force = force.normalize() * max_force;
}
let a = self.acceleration_mut();// Line 12
*a += *force / self.mass();//Line 13
self.accelerate(truncate);
}
fn accelerate(&mut self, truncate: bool) {
let v = self.velocity_mut();
*v += self.acceleration();

let max_speed = self.max_speed();

if v.square_length() > max_speed * max_speed && truncate {
*v = v.normalize() * max_speed;
}
}
fn velocity(&self) -> Vector2;
fn velocity_mut(&mut self) -> &mut Vector2;
fn acceleration(&self) -> Vector2;
fn acceleration_mut(&mut self) -> &mut Vector2;
fn max_speed(&self) -> f32;
fn max_speed_mut(&mut self) -> &mut f32;
fn max_force(&self) -> f32;
fn max_force_mut(&mut self) -> &mut f32;
fn mass(&self) -> f32;
fn mass_mut(&mut self) -> &mut f32;
}

struct Actor {
velocity: Vector2,
acceleration: Vector2,
max_speed: f32,
max_force: f32,
mass: f32
}

impl Physics for Actor {
fn velocity(&self) -> Vector2 {
self.velocity
}
fn velocity_mut(&mut self) -> &mut Vector2 {
&mut self.velocity
}
fn acceleration(&self) -> Vector2 {
self.acceleration
}
fn acceleration_mut(&mut self) -> &mut Vector2 {
&mut self.acceleration
}
fn mass(&self) -> f32 {
self.mass
}
fn mass_mut(&mut self) -> &mut f32 {
&mut self.mass
}
fn max_speed(&self) -> f32 {
self.max_speed
}
fn max_speed_mut(&mut self) -> &mut f32 {
&mut self.max_speed
}
fn max_force(&self) -> f32 {
self.max_force
}
fn max_force_mut(&mut self) -> &mut f32 {
&mut self.max_force
}
}

fn main() {

}


最佳答案

在还有可变借项的情况下您不能一成不变地借用的原因是,否则,您可能会使用可变借用来修改由不可变借用表示的基础数据。而且由于(显然)不应该更改不可变的借贷,因此借贷检查器无法承担风险(即使您“知道”可变的借贷也不会影响不可变的借贷)。
在这种情况下,我相信您可以通过在调用self.mass()之前将self.acceleration_mut()分配给本地来解决此问题

let mass = self.mass();
let a = self.acceleration_mut();
*a += *force / mass;
由于mass只是一个 f32,它在返回时被复制,因此将在下一行之前进行不可变的借用。

关于rust - 特质默认方法中的多次 self 借用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65729922/

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