相关疑难解决方法(0)

使用Rust编译器来防止忘记调用方法

我有一些像这样的代码:

foo.move_right_by(10);
//do some stuff
foo.move_left_by(10);
Run Code Online (Sandbox Code Playgroud)

最终我执行这两个操作非常重要,但我经常忘记在第一个之后执行第二个操作.它会导致很多错误,我想知道是否有一种习惯性的Rust方法来避免这个问题.当我忘记时,有没有办法让Rust编译器让我知道?

我的想法可能是某种类似的东西:

// must_use will prevent us from forgetting this if it is returned by a function
#[must_use]
pub struct MustGoLeft {
    steps: usize;
}

impl MustGoLeft {
    fn move(&self, foo: &mut Foo) {
        foo.move_left_by(self.steps);
    }
}

// If we don't use left, we'll get a warning about an unused variable
let left = foo.move_left_by(10);

// Downside: move() can be called multiple times which is still a bug
// Downside: left is still …
Run Code Online (Sandbox Code Playgroud)

api-design type-safety rust

8
推荐指数
2
解决办法
1424
查看次数

标签 统计

api-design ×1

rust ×1

type-safety ×1