【发布时间】:2018-11-02 01:54:55
【问题描述】:
我有这个通用类型:
pub struct MyContainer<T, S> {
array: Vec<T>,
get_size: S,
size: u32,
}
impl<T: Default, S> MyContainer<T, S>
where
S: Fn(&T) -> u32,
{
pub fn new(size: u32, get_size: S) -> MyContainer<T, S> {
let array = Vec::with_capacity(size as usize);
MyContainer {
array,
get_size,
size,
}
}
}
我可以使用编译器推演魔术轻松创建容器:
pub fn get_size_func(h: &House) -> u32 {
h.num_rooms
}
let container = MyContainer::new(6, get_size);
但是,当我尝试在另一个结构中实例化我的泛型类型时遇到了一个问题:
pub struct City {
suburbs: MyContainer<House, fn(&House) -> u32>,
}
impl City {
pub fn new(num_houses: u32) -> City {
let container = MyContainer::new(num_houses, get_size_func);
City { suburbs: container }
}
}
我明白了
error[E0308]: mismatched types
--> src/lib.rs:44:25
|
44 | City { suburbs: container }
| ^^^^^^^^^ expected fn pointer, found fn item
|
= note: expected type `MyContainer<_, for<'r> fn(&'r House) -> u32>`
found type `MyContainer<_, for<'r> fn(&'r House) -> u32 {get_size_func}>`
【问题讨论】:
-
Right way to have Function pointers in struct/How do I call a function through a member variable?的答案可能会回答您的问题。如果您同意,我们可以将此问题标记为已回答。
-
啊,我需要 fn 而不是 Fn。但是我现在遇到了一个案例,当我尝试调用 City 新函数时。感谢其他提示顺便说一句,如果我有其他问题,我会尝试创建一个新的 Rust 游乐场。
标签: rust