如何轻松借用 Vec<Vec<T>>作为 &[&[T]]? [英] How can you easily borrow a Vec<Vec<T>> as a &[&[T]]?

查看:29
本文介绍了如何轻松借用 Vec<Vec<T>>作为 &[&[T]]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何轻松地将向量的向量借用为切片的切片?

How can you easily borrow a vector of vectors as a slice of slices?

fn use_slice_of_slices<T>(slice_of_slices: &[&[T]]) {
    // Do something...
}

fn main() {
    let vec_of_vec = vec![vec![0]; 10];
    use_slice_of_slices(&vec_of_vec);
}

我会得到以下错误:

error[E0308]: mismatched types
 --> src/main.rs:7:25
  |
7 |     use_slice_of_slices(&vec_of_vec);
  |                         ^^^^^^^^^^^ expected slice, found struct `std::vec::Vec`
  |
  = note: expected type `&[&[_]]`
             found type `&std::vec::Vec<std::vec::Vec<{integer}>>`

我可以很容易地定义 use_slice_of_slices

I could just as easily define use_slice_of_slices as

fn use_slice_of_slices<T>(slice_of_slices: &[Vec<T>]) {
    // Do something
}

并且外部向量将作为切片借用,一切都将起作用.但是,如果只是为了论证,我想借用它作为切片呢?

and the outer vector would be borrowed as a slice and all would work. But what if, just for the sake of argument, I want to borrow it as a slice of slices?

假设从 &Vec&[&[T]] 的自动强制是不可能的,那么我该如何定义一个函数 borrow_vec_o​​f_vec 如下?

Assuming automatic coercing from &Vec<Vec<T>> to &[&[T]] is not possible, then how can I define a function borrow_vec_of_vec as below?

fn borrow_vec_of_vec<'a, T: 'a>(vec_of_vec: Vec<Vec<T>>) -> &'a [&'a [T]] {
    // Borrow vec_of_vec...
}

换句话说,我如何为Vec>实现Borrow<[&[T]]>?

To put it in another way, how could I implement Borrow<[&[T]]> for Vec<Vec<T>>?

推荐答案

不能.

根据定义,切片是现有元素集合上的视图.它不能凭空想象出新元素或现有元素的新视图.

By definition, a slice is a view on an existing collection of element. It cannot conjure up new elements, or new views of existing elements, out of thin air.

这是因为 Rust 泛型参数通常是不变量.也就是说,虽然 &Vec 可以在某种方式后转换为 &[T],但那些中的 T两个表达式必须匹配.

This stems from the fact that Rust generic parameters are generally invariants. That is, while a &Vec<T> can be converted as a &[T] after a fashion, the T in those two expressions MUST match.

一种可能的解决方法是让自己通用.

A possible work-around is to go generic yourself.

use std::fmt::Debug;

fn use_slice_of_slices<U, T>(slice_of_slices: &[U])
where
    U: AsRef<[T]>,
    T: Debug,
{
    for slice in slice_of_slices {
        println!("{:?}", slice.as_ref());
    }
}

fn main() {
    let vec_of_vec = vec![vec![0]; 10];
    use_slice_of_slices(&vec_of_vec);
}

不是强加元素应该是什么类型,而是接受任何类型......但设置一个界限,它必须被强制转换为[T].

Instead of imposing what the type of the element should be, you instead accept any type... but place a bound that it must be coercible to [T].

这几乎具有相同的效果,因为泛型函数只能将 [T] 作为切片操作.作为奖励,它适用于多种类型(任何可以强制转换为 [T] 的类型).

This has nearly the same effect, as then the generic function can only manipulate [T] as a slice. As a bonus, it works with multiple types (any which can be coerced into a [T]).

这篇关于如何轻松借用 Vec&lt;Vec&lt;T&gt;&gt;作为 &amp;[&amp;[T]]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆