简体   繁体   English

如果没有特质专业化,“借用”如何运作?

[英]How does `Borrow` work without trait specialization?

Currently, Rust does not have the feature "trait specialization" yet. 目前,Rust还没有“特质专业化”功能。 As far as I understand, this means that a trait can't be implemented more than once for one given type. 据我所知,这意味着对于一种给定类型,特征不能多次实现。 However, I noticed that the Borrow trait is implemented for T where T: ?Sized which are all non-reference types there are (right?). 但是,我注意到Borrow特性for T where T: ?Sized实现的for T where T: ?Sized ,它们都是非引用类型(对吧?)。 But it's also implemented for several other types, like Vec<T> , which looks like a specialization. 但它也实现了其他几种类型,如Vec<T> ,看起来像是一种专业化。

How is that working? 这怎么样? Is it compiler magic or did I misunderstand what trait specialization is? 它是编译器魔术还是我误解了什么特质专业化?

Short answer 简短的回答

In this case, trait specialization is not necessary, since the implementations are non-overlapping. 在这种情况下,特征专业化不是必需的,因为实现是非重叠的。

Long answer 答案很长

In the particular case of Vec<T> , there are many impls that apply to it. Vec<T>的特定情况下,有许多适用于它的impl。 For instance, the following: 例如,以下内容:

impl<T> Borrow<T> for T where T: ?Sized
impl<'a, T> Borrow<T> for &'a T where T: ?Sized
impl<'a, T> Borrow<T> for &'a mut T where T: ?Sized
// other implementations are omitted for conciseness

According to those implementations, the compiler can deduce the following: 根据这些实现,编译器可以推断出以下内容:

  1. Vec<T> implements Borrow<Vec<T>> Vec<T>实现Borrow<Vec<T>>
  2. &'a Vec<T> implements Borrow<Vec<T>> &'a Vec<T>实现Borrow<Vec<T>>
  3. &'a mut Vec<T> implements Borrow<Vec<T>> &'a mut Vec<T>实现Borrow<Vec<T>>

However, none of them implements Borrow<[T]> for Vec<T> . 但是,它们都没有为Vec<T>实现Borrow<[T]> Vec<T> Since that implementation is not provided, you are free to provide your own: 由于未提供该实施,您可以自由提供:

impl<T> Borrow<[T]> for Vec<T>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM