gpt4 book ai didi

rust - 您能否在一个位置更新一个数字并在引用的任何地方进行更改?

转载 作者:行者123 更新时间:2023-12-03 11:41:01 24 4
gpt4 key购买 nike

我想编写一个程序,该程序将具有许多(也许是几十到数百个)对相同数字的引用,例如“x”,并且每秒将被更新多次。因此,我只想在一个位置上更改编号,并使所有引用自动更新,而不必重新分配它们(再次,因为可能有数百个引用,导致数百次重新分配。)。如果我可以只在一个地方更新数字,那么我可以立即运行数百个product()更新。
下面是我对此的尝试,其中有两个结构引用同一f64内存。我只想更新一次x,然后更新我的结构(thing1和Thing2)的所有实例,以正确计算product

#[derive(Debug)]
struct Thing<'a> {
high: &'a f64,

low: &'a f64,
}

impl Thing<'_> {
pub fn product(&self) -> f64 {
*self.high * *self.low
}
}

fn main() {
let mut x: f64 = 42.01;
let y: f64 = 7.95;
let w: f64 = 99.9;
let mut thing1: Thing = Thing { high: &w, low: &x };
let mut thing2: Thing = Thing { high: &y, low: &x };
println!("Before {:?} {}", thing1, thing1.product());
println!("Before {:?} {}", thing2, thing2.product());

// I want to swap or copy in a new value for the reference x, because
// it appears multiple times in different `Thing`s.
x = 500.7_f64;
println!("After {:?} {}", thing1, thing1.product());
println!("After {:?} {}", thing2, thing2.product());
}
上面的代码无法编译并出现以下错误:
error[E0506]: cannot assign to `x` because it is borrowed
--> src/main.rs:25:5
|
18 | let mut thing1: Thing = Thing { high: &w, low: &x };
| -- borrow of `x` occurs here
...
25 | x = 500.7_f64;
| ^^^^^^^^^^^^^ assignment to borrowed `x` occurs here
26 | println!("After {:?} {}", thing1, thing1.product());
| ------ borrow later used here

最佳答案

您可以使用 Cell 及其表亲 RefCell ,用于修改共享值的用例:

use std::cell::Cell;

#[derive(Debug)]
struct Thing<'a> {
high: &'a Cell<f64>,
low: &'a Cell<f64>,
}

impl Thing<'_> {
pub fn product(&self) -> f64 {
self.high.get() * self.low.get()
}
}

fn main() {
let x = Cell::new(42.01);
let y = Cell::new(7.95);
let w = Cell::new(99.9);
let thing1: Thing = Thing { high: &w, low: &x };
let thing2: Thing = Thing { high: &y, low: &x };
println!("Before {:?} {}", thing1, thing1.product());
println!("Before {:?} {}", thing2, thing2.product());

x.set(500.7_f64);
println!("After {:?} {}", thing1, thing1.product());
println!("After {:?} {}", thing2, thing2.product());
}
Playground

关于rust - 您能否在一个位置更新一个数字并在引用的任何地方进行更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65257264/

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