我正在尝试将结构中的状态与改变状态的回调捆绑在一起。当我使用托管指针时它工作正常:
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));
接下来,我想将此结构发送到另一个任务,因此必须在各处切换到唯一指针。我无法做到这一点:“错误:过时的语法:常量或可变拥有的指针”
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));
有什么建议么?跨任务发送回调的更好方法?