我有三个示例,一个使用Vec,一个使用SmallVec,另一个使用我自己的SmallVec实现。使用Vec和我自己的SmallVec的那些会编译,但是使用真正的SmallVec的那些不会编译。

使用Vec的工作示例

use std::borrow::Cow;
use std::collections::HashMap;

pub trait MyTrait {
    fn get_by_id(&self, id: usize) -> &ItemTraitReturns;
}

/// IMPORTANT PART IS HERE: `Vec<Cow<'a, str>>`
pub struct ItemTraitReturns<'a>(Vec<Cow<'a, str>>);

/// this implementation only takes items with static lifetime (but other implementations also might have different lifetimes)
pub struct MyTraitStruct {
    map: HashMap<usize, ItemTraitReturns<'static>>,
}

impl MyTrait for MyTraitStruct {
    fn get_by_id(&self, id: usize) -> &ItemTraitReturns {
        let temp: &ItemTraitReturns<'static> = self.map.get(&id).unwrap();
        // Works as expected: I expect that I can return `&ItemTraitReturns<'_>`
        // when I have `&ItemTraitReturns<'static>` (since 'static outlives everything).
        temp
        // Will return `&ItemTraitReturns<'_>`
    }
}

SmallVec的失败示例

使用SmallVec而不是Vec且没有其他更改。

use smallvec::SmallVec;
use std::borrow::Cow;
use std::collections::HashMap;

pub trait MyTrait {
    fn get_by_id(&self, id: usize) -> &ItemTraitReturns;
}

/// IMPORTANT PART IS HERE: Uses SmallVec instead of Vec
pub struct ItemTraitReturns<'a>(SmallVec<[Cow<'a, str>; 2]>);

/// this implementation only takes items with static lifetime (but other implementations also might have different lifetimes)
pub struct MyTraitStruct {
    map: HashMap<usize, ItemTraitReturns<'static>>,
}

impl MyTrait for MyTraitStruct {
    fn get_by_id(&self, id: usize) -> &ItemTraitReturns {
        let temp: &ItemTraitReturns<'static> = self.map.get(&id).unwrap();
        temp
    }
}

error[E0308]: mismatched types
  --> src/lib.rs:23:9
   |
23 |         temp
   |         ^^^^ lifetime mismatch
   |
   = note: expected type `&ItemTraitReturns<'_>`
              found type `&ItemTraitReturns<'static>`
note: the anonymous lifetime #1 defined on the method body at 18:5...
  --> src/lib.rs:18:5
   |
18 | /     fn get_by_id(&self, id: usize) -> &ItemTraitReturns {
19 | |         let temp: &ItemTraitReturns<'static> = self.map.get(&id).unwrap();
20 | |         // Error:
21 | |         //    = note: expected type `&demo2::ItemTraitReturns<'_>`
22 | |         //              found type `&demo2::ItemTraitReturns<'static>`
23 | |         temp
24 | |     }
   | |_____^
   = note: ...does not necessarily outlive the static lifetime

我自己的SmallVec的工作示例

当我实现自己的(非常幼稚的)SmallVec<[T; 2]>(称为NaiveSmallVec2<T>)时,该代码也会编译...非常奇怪!

use std::borrow::Cow;
use std::collections::HashMap;

/// This is a very naive implementation of a SmallVec<[T; 2]>
pub struct NaiveSmallVec2<T> {
    item1: Option<T>,
    item2: Option<T>,
    more: Vec<T>,
}

impl<T> NaiveSmallVec2<T> {
    pub fn push(&mut self, item: T) {
        if self.item1.is_none() {
            self.item1 = Some(item);
        } else if self.item2.is_none() {
            self.item2 = Some(item);
        } else {
            self.more.push(item);
        }
    }

    pub fn element_by_index(&self, index: usize) -> Option<&T> {
        match index {
            0 => self.item1.as_ref(),
            1 => self.item2.as_ref(),
            _ => self.more.get(index - 2),
        }
    }
}

pub trait MyTrait {
    fn get_by_id(&self, id: usize) -> &ItemTraitReturns;
}

/// IMPORTANT PART IS HERE: Uses NaiveSmallVec2
pub struct ItemTraitReturns<'a>(NaiveSmallVec2<Cow<'a, str>>);

/// only takes items with static lifetime
pub struct MyTraitStruct {
    map: HashMap<usize, ItemTraitReturns<'static>>,
}

impl MyTrait for MyTraitStruct {
    fn get_by_id(&self, id: usize) -> &ItemTraitReturns {
        let temp: &ItemTraitReturns<'static> = self.map.get(&id).unwrap();
        // astonishingly this works!
        temp
    }
}

我希望SmallVec版本能够像Vec版本一样进行编译。我不明白为什么在某些情况下(对于Vec)&ItemTraitReturns<'static>可以转换为&ItemTraitReturns<'_>,而在某些情况下(SmallVec)却不可能(我看不到Vec/SmallVec的影响)。

我不想更改此特征的生命周期:

pub trait MyTrait {
    fn get_by_id(&self, id: usize) -> &ItemTraitReturns;
}

...因为使用特质时我不关心生命周期(这应该是实现细节)...但仍然想使用SmallVec

最佳答案

这种差异似乎是由VecSmallVec之间的差异引起的。虽然Vec<T>T中是协变的,但SmallVec似乎是不变的。结果,即使生存期SmallVec<[&'a T; 1]>超过SmallVec<[&'b T; 1]>,而且'a仍是安全的,也无法将'b转换为SmallVec。这是触发编译器错误的最小示例:

fn foo<'a, T>(x: SmallVec<[&'static T; 1]>) -> SmallVec<[&'a T; 1]> {
    x  // Compiler error here: lifetime mismatch
}

fn bar<'a, T>(x: Vec<&'static T>) -> Vec<&'a T> {
    x  // Compiles fine
}

这似乎是ojit_code的缺点。方差是由编译器自动确定的,有时要使编译器确信类型是协变的,这是很麻烦的。

有一个open Github issue for this problem

不幸的是,我不知道一种基于类型的公共(public)接口(interface)来弄清类型的变化的方法。差异未包含在文档中,并且取决于类型的私有(private)实现细节。您可以阅读有关in the language referencein the Nomicon的更多信息。

10-06 09:11