gpt4 book ai didi

rust - Rust 中的方法数组

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

我正在尝试用 Rust 编写一个请求“路由器”:一个与匹配发生时要调用的函数关联的表达式列表。这些函数可能是来自各种对象的方法,这当然会导致借用检查器提示。这是我想要的示例:

use std::collections::HashMap;

struct Foo(bool);

impl Foo {
fn say(&self) {
println!("I'm {}", self.0);
}
fn morph(&mut self) {
self.0 = !self.0;
}
}

fn main() {
let mut foo = Foo(true);

let mut routes: HashMap<String, Box<FnMut()>> = HashMap::new();
routes.insert("foo/say".to_string(), Box::new(|| foo.say())); //< First (immutable) borrow of foo
routes.insert("foo/morph".to_string(), Box::new(|| foo.morph())); //< Second (mutable) borrow of foo
routes.insert("bar".to_string(), Box::new(|| println!("hello"))); //< Compiler also says immutable foo is used here
}

我理解为什么借用检查器对此不满意,但我想知道在 Rust 中实现它的惯用方式是什么

旁注:任何有关获取列表/数组/ HashMap 或任何异构函数集合的最佳方法的一般性评论都将不胜感激。

最佳答案

解决方案非常简单,真的。因为您将需要一个允许您按需获得可变借用的结构,所以您将需要一个 RwLock。 .因为我猜你正在构建的是一个 HTTP 路由器,以绕过 Foo 上的生命周期要求。 ,您将要包装 RwLockArc ,像这样:

use std::collections::HashMap;
use std::sync::{Arc, RwLock};

struct Foo(bool);

impl Foo {
fn say(&self) {
println!("I'm {}", self.0);
}
fn morph(&mut self) {
self.0 = !self.0;
}
}

fn main() {
let mut foo = Arc::new(RwLock::new(Foo(true)));

let mut routes: HashMap<String, Box<FnMut()>> = HashMap::new();
routes.insert("foo/say".to_string(), Box::new(|| foo.read().unwrap().say())); //< First (immutable) borrow of foo
routes.insert("foo/morph".to_string(), Box::new(|| foo.write().unwrap().morph())); //< Second (mutable) borrow of foo
routes.insert("bar".to_string(), Box::new(|| println!("hello"))); //< Compiler also says immutable foo is used here
}

请注意,我滥用了一切都可以借用的事实 foo为此只读。如果你需要 move闭包中的东西,Arc工具 Clone ,所以您绝对应该利用这一点。

其余的很好 - 只要您的闭包都具有相同的签名,装箱它们并将它们存储在任何集合中是惯用的。

关于rust - Rust 中的方法数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58346865/

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