为什么 .push() 方法采用 &mut Vec<T> 而不是取得 Vec<T> 的所有权(然后将其返回)?

问题描述 投票:0回答:1

.push()
上的
Vec<T>
方法将
&mut Vec<T>
作为其参数,新元素的添加是一个副作用。

决定反对

push
的原因是什么?它是纯函数式的,因此它的 API 看起来像这样:

fn push(mut self, elem) -> Self

拥有

Vec<T>
会不会在某种程度上不符合人体工程学?我不认为移动它会对性能产生重大影响,因为
Vec
只是一个胖指针。

rust
1个回答
0
投票

采用可变引用更灵活,但没有什么可以阻止您创建自己的特征并将其实现为向量。

pub trait Acc {
  type Item;

  fn acc(self, item: Self::Item) -> Self;
}

impl<Item> Acc for Vec<Item> {
  type Item = Item;

  fn acc<'a>(mut self, item: Self::Item) -> Self {
    self.push(item);
    self
  }
}

我个人在我的一个图书馆中定义了这一点:

/// Abstracts something which can push Item into self
pub trait Push {
  /// Item stocked in the collection
  type Item;
  /// Represent a way to access Item in the collection directly after push
  type ItemView<'a>
  where
    Self: 'a;

  /// push an item into a collection, no guarantee on ordering.
  fn push<'a>(&'a mut self, item: Self::Item) -> Self::ItemView<'a>;
}

/// This is very usefull to be use on combinator like fold.
/// For example, `.fold_bounds(.., Vec::new, Acc::acc)`.
pub trait Acc {
  /// Item stocked in the collection
  type Item;

  /// Accumulate item into Self. For example, for a vector that simply a push.
  fn acc(self, item: Self::Item) -> Self;
}

impl<T> Acc for T
where
  Self: Push,
{
  type Item = <T as Push>::Item;

  fn acc(mut self, item: Self::Item) -> Self {
    self.push(item);
    self
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.