首页
注册
登录
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请
登录
›
The Rust Programming Language
›
github.com/mozilla/rust
V2EX
›
Rust
rust 如何实现闭包 Vec?
gramyang
·
2020-05-19 21:30:23 +08:00
· 3086 次点击
这是一个创建于 1957 天前的主题,其中的信息可能已经有所发展或是发生改变。
函数指针 Vec 是可以实现的,但是不知道如何实现闭包 Vec 。
type Bibao = dyn Fn(String)->String + 'static;
pub fn close_test4(){
let a = "456";
let b1: Bibao = move |mut s:String|{
s.push_str(a);
s
};
let mut v = Vec::new();
op1(b1,&v);
v.get(0)(String::from("123"));
}
fn op1<T:Fn(String) ->String>(t:T,mut v:&Vec<T>){
v.push(t);
}
报错:expected trait object `dyn std::ops::Fn`, found closure
求大佬指点。
第 1 条附言 ·
2020-05-20 13:31:07 +08:00
修改了一下终于可行了,代码:
type Boo = Box<dyn Fn(i32) -> String>;
fn op1(x:i32, y:String) -> impl Fn(i32) -> String {
move |s:i32| {
let mut a = String::new();
a.push_str((x+s).to_string().as_str());
a.push_str(y.as_str());
a
}
}
fn op2(x:i32) -> impl Fn(i32) -> String{
move |s:i32| {
let mut a = String::new();
a.push_str((x+s).to_string().as_str());
a
}
}
fn op3(y:String) ->impl Fn(i32) -> String{
move |s:i32| {
let mut a = String::new();
a.push_str((s).to_string().as_str());
a.push_str(y.as_str());
a
}
}
pub fn c_t5(){
let c1 = Box::new(op1(10,String::from("ab")));
let c2 = Box::new(op2(20));
let c3 = Box::new(op3(String::from("cd")));
let mut vec:Vec<Boo> = Vec::new();
vec.push(c1);
vec.push(c2);
vec.push(c3);
println!("{} {} {}",vec.get(0).unwrap()(30),vec.get(1).unwrap()(30),
vec.get(2).unwrap()(30));//40ab 50 30cd
}
string
vec
mut
闭包
4 条回复
•
2020-05-20 14:38:47 +08:00
1
sosilver
2020-05-19 22:32:07 +08:00 via Android
用 Box<dyn T>
2
gwy15
2020-05-19 22:46:04 +08:00
我试了下没问题啊
https://gist.github.com/gwy15/28a3bdd1228dc82dd64c2d49b729bda0
3
gramyang
OP
2020-05-20 13:29:10 +08:00
@
sosilver
可行!
4
sosilver
2020-05-20 14:38:47 +08:00 via Android
@
gwy15
这样写只能装一个 closure 。因为不同的 closure 的类型是不同的,Vec<T>的推导类型由第一个放进去的决定,然后就放不进去其它的了。
关于
·
帮助文档
·
自助推广系统
·
博客
·
API
·
FAQ
·
实用小工具
·
4063 人在线
最高记录 6679
·
Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 24ms ·
UTC 10:11
·
PVG 18:11
·
LAX 03:11
·
JFK 06:11
Developed with
CodeLauncher
♥ Do have faith in what you're doing.
❯