gpt4 book ai didi

rust - 如何测试是否调用了回调闭包?

转载 作者:行者123 更新时间:2023-12-05 01:50:10 25 4
gpt4 key购买 nike

考虑我的结构 WareHouse,它有一个 watch 函数,它接受一个闭包作为参数。

该结构还有一个 update 函数,它更新一个路径和一个值,然后应该调用传递给 watch 函数的闭包(如果适用)。

我如何验证当我调用 watch(callback) 后更新回调函数被触发?

我试过:

#[test]
fn calls_watcher_on_update() {
let mut w = WareHouse::new();
let mut called = false;
// set a watcher
w.watch(move|| {
println!("watcher called");
called = true;
});
w.update("/foo", "baz").unwrap();
assert!(called);
}

最佳答案

当您尝试移动实现 Copy 的值时, 它被复制了。所以你的闭包捕获了 called 的值它被创建的那一刻; called闭包内部和外部实际上是两个不同的变量。

您甚至应该收到警告,例如:

warning: value captured by `called` is never read

相反,考虑捕获 Cell<bool>引用。我推断你需要一个 Cell在这里是因为通过可变引用捕获需要 w在您可以读取 assert!() 中的值之前删除闭包否则你会得到一个“不能在已经借用的情况下可变借用”的错误。

use std::cell::Cell;

fn main() {
// Doesn't work right; called is copied into the closure, not moved.
{
let mut called = false;
let mut closure = move || {
called = true;
println!("(A) In closure, called is {called}");
};
closure();
println!("(A) Outside of closure, called is {called}");
}

// Workes correctly; the closure captures a reference to the cell.
{
let called = Cell::new(false);
let closure = || {
called.set(true);
println!("(B) In closure, called is {}", called.get());
};
closure();
println!("(B) Outside of closure, called is {}", called.get());
}
}

这将输出:

(A) In closure, called is true
(A) Outside of closure, called is false
(B) In closure, called is true
(B) Outside of closure, called is true

( Playground )

关于rust - 如何测试是否调用了回调闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73340360/

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