我想做这个:
struct Point {
x: i32,
y: i32,
}
impl Point {
fn up(&self) {
self.y += 1;
}
}
fn main() {
let p = Point { x: 0, y: 0 };
p.up();
}
Run Code Online (Sandbox Code Playgroud)
但是这段代码抛出了编译器错误:
error[E0594]: cannot assign to field `self.y` of immutable binding
--> src/main.rs:8:9
|
7 | fn up(&self) {
| ----- use `&mut self` here to make mutable
8 | self.y += 1;
| ^^^^^^^^^^^ cannot mutably borrow field of immutable binding
Run Code Online (Sandbox Code Playgroud) 我在Haskell中有这个代码:
import Control.Monad.Trans.State
simpleState = state (\x -> (x, x + 1))
runUntil :: (s -> Bool) -> State s a -> State s a
runUntil f s = do
s' <- get
-- Here I want to print value of s' to console
if f s'
then s >> runUntil f s
else s
main :: IO ()
main = do
let (x,s) = runState (runUntil (< 10) simpleState) 0
putStrLn $ "State = " ++ (show s) ++ …Run Code Online (Sandbox Code Playgroud) 我有解决c-union结构XEvent的问题.
我在Rust中试验Xlib和X Record Extension.我用rust-bindgen生成ffi-bindings .所有代码都托管在github alxkolm/rust-xlib-record上.
当我尝试从XEvent结构中提取数据时,在src/main.rs:106行发生了故障.
let key_event: *mut xlib::XKeyEvent = event.xkey();
println!("KeyPress {}", (*key_event).keycode); // this always print 128 on any key
我的程序听取关键事件并打印出来keycode.但是我按下的任何按键总是128.我认为从C union类型到Rust类型的这种错误转换.
XEvent的定义从这里开始src/xlib.rs:1143.这是c-union.原始C定义在这里.
GitHub中的代码可以通过cargo run命令运行.它编译没有错误.
我做错了什么?