gpt4 book ai didi

generics - 如何在结构中存储闭包对象?

转载 作者:行者123 更新时间:2023-12-03 11:32:07 25 4
gpt4 key购买 nike

我不知道如何在结构中存储闭包对象。闭包对象的参数和返回值是已知的。这是我的浓缩代码:

struct Instr<F>
where F: Fn([i32;4],[i32;3]) -> [i32;4]
{
name: String,
op: F
}

fn main()
{
// Simple example showing the difficulty:
let tmp : Instr<Fn([i32;4],[i32;3]) -> [i32;4]> = Instr { name: "asd".to_string(), op: |a,b| a};

// What I really want is something more like this:
// let instrs = vec![
// Instr { name: "asdf", op: |a,b| a },
// Instr { name: "qwer", op: |a,b| a }
// ];
}

坦率地说,我不明白这些错误是什么意思。在我看来这很简单。闭包有一个类型和一个已知的大小。将它存储在相同类型的类型化字段中应该很简单。对吧?

按照错误消息的建议尝试添加 F: ?Sized 并不能修复“编译时大小未知”错误。

有人可以帮我正确编译吗?

error[E0277]: the size for values of type `dyn Fn([i32; 4], [i32; 3]) -> [i32; 4]` cannot be known at compilation time
--> a.rs:11:15
|
1 | struct Instr<F>
| - required by this bound in `Instr`
...
11 | let tmp : Instr<Fn([i32;4],[i32;3]) -> [i32;4]> = Instr { name: "asd".to_string(), op: |a,b| a};
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `dyn Fn([i32; 4], [i32; 3]) -> [i32; 4]`
help: you could relax the implicit `Sized` bound on `F` if it were used through indirection like `&F` or `Box<F>`
--> a.rs:1:14
|
1 | struct Instr<F>
| ^ this could be changed to `F: ?Sized`...
2 | where F : Fn([i32;4],[i32;3]) -> [i32;4]
| - ...if indirection was used here: `Box<F>`
...
5 | op : F
| - ...if indirection was used here: `Box<F>`

error[E0277]: the size for values of type `dyn Fn([i32; 4], [i32; 3]) -> [i32; 4]` cannot be known at compilation time
--> a.rs:11:55
|
1 | / struct Instr<F>
2 | | where F : Fn([i32;4],[i32;3]) -> [i32;4]
3 | | {
4 | | name : String,
5 | | op : F
6 | | }
| |_- required by `Instr`
...
11 | let tmp : Instr<Fn([i32;4],[i32;3]) -> [i32;4]> = Instr { name: "asd".to_string(), op: |a,b| a};
| ^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `dyn Fn([i32; 4], [i32; 3]) -> [i32; 4]`

error[E0308]: mismatched types
--> a.rs:11:92
|
11 | let tmp : Instr<Fn([i32;4],[i32;3]) -> [i32;4]> = Instr { name: "asd".to_string(), op: |a,b| a};
| ^^^^^^^ expected trait object `dyn Fn`, found closure
|
= note: expected trait object `dyn Fn([i32; 4], [i32; 3]) -> [i32; 4]`
found closure `[closure@a.rs:11:92: 11:99]`

最佳答案

不同的闭包有不同的大小,所以你不能在结构中存储“原始闭包”或“原始特征对象”,它们必须在一个指针后面,所以你可以将它们放在一个Box像这样:

struct Instr {
name: String,
op: Box<dyn Fn([i32; 4], [i32; 3]) -> [i32; 4]>,
}

fn main() {
let instrs = vec![
Instr { name: "asdf".into(), op: Box::new(|a,b| a) },
Instr { name: "qwer".into(), op: Box::new(|a,b| a) }
];
}

playground

关于generics - 如何在结构中存储闭包对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65756096/

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