【问题标题】:How to call a function that returns a generic slice type on Rust如何在 Rust 上调用返回通用切片类型的函数
【发布时间】:2021-01-22 02:19:47
【问题描述】:

我正在阅读以下代码from here

#[inline]
pub fn plane<T: Component>(&self, index: usize) -> &[T] {
    if index >= self.planes() {
        panic!("out of bounds");
    }

    if !<T as Component>::is_valid(self.format()) {

如您所见,plane 函数返回一个泛型类型的切片。这是否意味着我需要始终像这样调用这个函数:plane::&lt;SomeType&gt;::(my_index)

问题是我不知道要使用哪种类型,它不是整个结构的类型,只是这个函数和其他的。

例如,我看到了

unsafe impl Component for [u8; 3] {
    #[inline(always)]
    fn is_valid(format: format::Pixel) -> bool {
        format == format::Pixel::RGB24 || format == format::Pixel::BGR24
    }
}

这是否意味着T 可以是[u8; 3],因此plane 可以返回&amp;[&amp;[u8; 3]]

所以我应该打电话给self.plane::&lt;u8&gt;(index) 吗?我试过了,但我在u8 上得到了wrong number of type arguments: expected 0, found 1。我也不认为&amp;[&amp;[u8; 3]] 是对的。

【问题讨论】:

    标签: rust


    【解决方案1】:

    这是否意味着我需要总是像这样调用这个函数:plane::&lt;SomeType&gt;(my_index)

    不,如果 Rust 可以推断出SomeType,那么您不必显式提供它。如果你是例如将 plane 的结果分配给您已指定类型的变量,您不必在调用中提供它。

    这是否意味着T 可以是[u8; 3],因此飞机可以返回&amp;[&amp;[u8; 3]]

    如果T[u8; 3],则平面返回&amp;[[u8; 3]]

    【讨论】:

      猜你喜欢
      • 2022-01-07
      • 1970-01-01
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      • 1970-01-01
      • 1970-01-01
      • 2019-11-26
      相关资源
      最近更新 更多