Rust中的"<[_]>"是什么?

36
vec!宏的实现中,有这个规则:
($($x:expr),+ $(,)?) => (
    $crate::__rust_force_expr!(<[_]>::into_vec(box [$($x),+]))
);

那个<[_]>到底是什么意思呢?


6
呼,Rust通常相当易读且直观,但<[_]>::看起来像是从esolang中抽出来的东西。 - Silvio Mayolo
2个回答

30

分解语法的特定部分:


1
参考:合格的路径 - IInspectable
这个答案是 Rust Macro 书中 <[()]> 的完美解释。https://danielkeep.github.io/tlborm/book/blk-counting.html#slice-length - Peter

15

让我们逐步看看 <[_]>::into_vec(box [$($x),+]) 是如何生成 Vec 的:

  1. [$($x),+] expands to an array of input elements: [1, 2, 3]
  2. box ... puts that into a Box. box expressions are nightly-only syntax sugar for Box::new: box 5 is syntax sugar for Box::new(5) (actually it's the other way around: internally Box::new uses box, which is implemented in the compiler)
  3. <[_]>::into_vec(...) calls the to_vec method on a slice containing elements that have an inferred type ([_]). Wrapping the [_] in angled brackets is needed for syntactic reasons to call an method on a slice type. And into_vec is a function that takes a boxed slice and produces a Vec:
    pub fn into_vec<A: Allocator>(self: Box<Self, A>) -> Vec<T, A> {
        // ...
    }
    

这个可以用更简单的方式来实现,但是这段代码经过优化以提高vec!的性能。例如,由于Vec的大小可以预先知道,因此into_vec在构建期间不会导致Vec重新分配。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接