【问题标题】:Embedding a Rust generic with generic functions inside another struct在另一个结构中嵌入带有泛型函数的 Rust 泛型
【发布时间】: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}>`

这是Rust playground that reproduces the problem

【问题讨论】:

标签: rust


【解决方案1】:

这个问题有两个答案:

  1. 创建容器时指定类型参数。我不知道为什么会这样,但确实有效:

    let container = MyContainer::<House, fn(&House) -> u32>::new(num_houses, get_size_func);
    
  2. 您还可以定义一个通用函数,该函数调用通用特征以增加踢球。例如:

     let container = MyContainer::<House, fn(&House) -> u32>::new(num_houses, get_size_func2::<House>);
    

    get_size_func2 将是一个 trait bound 泛型函数。

这里是the full playground。对于这两种解决方案,类型参数都是必需的,而不是在City::new 函数中推导出来的。

【讨论】:

  • What is a function signature and type? — 每个函数都有一个唯一的类型,它不是函数指针类型。
  • @Shepmaster 你能暗示这是为什么吗?似乎要具有通用函数(例如,采用两个 u64 并返回另一个 u64 的二元运算符表)需要使用 as fn(x) -&gt; y 强制转换重复函数签名。有什么好处?
  • @Shepmaster 只是想知道你是否知道“每个函数都有一个唯一的类型”特性被添加到 Rust 的原因。比如,解决了什么问题。我只是在尝试将一系列函数应用于某些输入时发现了它,并且很惊讶如果不使用 as 将它们转换为更通用的函数指针,这是不可能的。
  • @Shepmaster 哦,刚刚注意到您在 Playground 中的示例,这不是必需的。现在我比以往任何时候都更加困惑! :D
猜你喜欢
  • 2020-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-08
  • 1970-01-01
  • 2014-01-07
  • 1970-01-01
相关资源
最近更新 更多