gpt4 book ai didi

rust - Rust 中状态和回调的唯一指针

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

我正在尝试将结构中的状态与改变状态的回调捆绑在一起。当我使用托管指针时它工作正常:

struct StateAndCallbacks01 {
state: @mut int,
inc: @fn(),
dec: @fn()
}

let state01: @mut int = @mut 0;
let inc01: @fn() = || {
*state01 += 1;
};
let dec01: @fn() = || {
*state01 -= 1;
};
let state_cbs_01 = @StateAndCallbacks01 {
state: state01,
inc: inc01,
dec: dec01
};
(state_cbs_01.inc)();
println(fmt!("state: %d", *state_cbs_01.state));
(state_cbs_01.dec)();
println(fmt!("state: %d", *state_cbs_01.state));

接下来,我想将这个结构发送给另一个任务,因此必须到处切换到唯一指针。我无法完成这项工作:“错误:过时的语法:const 或可变拥有的指针”

struct StateAndCallbacks02 {
state: ~mut int,
inc: ~fn(),
dec: ~fn()
}

let state02: ~mut int = ~mut 0;
let inc02: ~fn() = || {
*state02 += 1;
};
let dec02: ~fn() = || {
*state02 -= 1;
};
let state_cbs_02 = ~StateAndCallbacks02 {
state: state02,
inc: inc02,
dec: dec02
};

let (port, chan): (Port<bool>, Chan<bool>) = stream();
do spawn {
(state_cbs_02.inc)();
println(fmt!("state: %d", *state_cbs_02.state));
(state_cbs_02.dec)();
println(fmt!("state: %d", *state_cbs_02.state));
chan.send(true);
};
let result = port.recv();
println(fmt!("result: %s", result));

有什么建议吗?有没有更好的方法来跨任务发送回调?

最佳答案

您可以将方法添加到结构中,而不是将函数作为字段保留在结构中。

struct Foo {
data: int
}

impl Foo {
fn inc(&mut self) {
self.data += 1;
}
}

impl 语法允许您在结构上定义方法。您稍后可以调用它:

let mut my_foo = Foo { data: 0 };
my_foo.inc();

您必须将 my_foo 声明为可变的,因为 inc 方法需要对其进行可变引用。

过时语法错误的原因是因为不推荐使用 ~mut 0,因为可变性由谁“拥有”对象决定。您需要做的是 let mut foo = ~0。变量 foo 是“所有者”,因此是您声明可变性的地方。 @-指针的特殊之处在于它们不继承可变性并且由任务本地 GC 管理。 (Rust tutorial 的第 8 和第 9 节更好地解释了这一点)

因此,将所有这些放在一起,您可以像这样编写原始代码:

struct State {
data: int
}

impl State {
fn inc(&mut self) {
self.data += 1;
}

fn dec(&mut self) {
self.data -= 1;
}
}

fn main() {

let state = State {
data: 0
};

let (port, chan) = stream();

do spawn {

let mut state = state;

state.inc();
println(fmt!("State: %d", state.data));
state.dec();
println(fmt!("State: %d", state.data));

chan.send(true);
};

let result = port.recv();
println(fmt!("Result: %?", result));

}

关于rust - Rust 中状态和回调的唯一指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16754164/

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