仅当impl标记为“default”时,关联类型和类型参数之间不匹配

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

以下代码导致错误(Playground

#![feature(specialization)]

trait Foo {
    type Assoc;
    fn foo(&self) -> &Self::Assoc;
}

default impl<T> Foo for T {
    type Assoc = T;
    fn foo(&self) -> &Self::Assoc {
        self
    }
}

错误:

error[E0308]: mismatched types
  --> src/main.rs:20:9
   |
20 |         self
   |         ^^^^ expected associated type, found type parameter
   |
   = note: expected type `&<T as Foo>::Assoc`
              found type `&T`

这很奇怪,因为<T as Foo>::AssocT,所以它应该工作。甚至更奇怪:当我从impl中删除default关键字时,它可以工作(但当然,在我的真实代码中,我需要将impl标记为default)。

在特征定义(Playground)中提供默认值时会发生相同的错误:

#![feature(specialization)]
#![feature(associated_type_defaults)]

trait Foo {
    type Assoc = Self;
    fn foo(&self) -> &Self::Assoc {
        self
    }
}

这里发生了什么?这是编译器错误吗?或者 - 这就是我问这个问题的原因 - 这个错误是否有意义,因为我还没有理解专业化方面有什么特别之处?如果这是一个错误,mem::transmute肯定是安全的,riiiight?

rust traits
1个回答
5
投票

Specialization功能没有显示稳定的迹象,主要是因为soundness concerns,所以你应该期待一些问题。

你有这个:

#![feature(specialization)]

trait Foo {
    type Assoc;
    fn foo(&self) -> &Self::Assoc;
}

default impl<T> Foo for T {
    type Assoc = T;
    fn foo(&self) -> &Self::Assoc {
        self
    }
}

但想象一下,您添加了另一个具有自己的关联类型但没有实现foo的实现。这个实现的foo将从另一个不太具体的实现中“继承”:

impl<T: SomeConstraint> Foo for T {
    type Assoc = NotT;
}

那就有问题了。你的foo将返回一个T但是,每当T是SomeConstraint时就会出现类型不匹配,因为它应该返回一个NotT

RFC 2532 — associated type defaults在其Future Work section中提到了一个可能的解决方案。假设的default块可用于指示相关类型和方法需要一起专用。然而,没有迹象表明何时考虑包含这样的特征。

© www.soinside.com 2019 - 2024. All rights reserved.