简体   繁体   English

尽管有适当的特征绑定,但特征相关的 const 在特征定义上下文中不可用

[英]Trait associated const is not available in trait definition context despite appropriate trait bound

Here's what I'm working on ( playground ):这是我正在做的事情( 操场):

pub trait DisplayWidth {
    const DISPLAY_WIDTH: usize;

    fn chunks<'a>(s: &'a str) -> Chunks<'a, Self> {
        Chunks(s.chars(), PhantomData)
    }
}

pub struct Chunks<'a, T: ?Sized>(std::str::Chars<'a>, PhantomData<T>);

impl<'a, T: DisplayWidth> Iterator for Chunks<'a, T> {
    // 4 bytes in a max-width char
    type Item = SmallString<[u8; 4 * T::DISPLAY_WIDTH]>;

    fn next(&mut self) -> Option<Self::Item> {
        let mut s = SmallString::new();
        for _ in 0..T::DISPLAY_WIDTH {
            s.push(self.0.next()?);
        }
        Some(s)
    }
}

This generates an E0599, but only for the type Item definition:这会生成一个 E0599,但仅适用于type Item定义:

error[E0599]: no associated item named `DISPLAY_WIDTH` found for type parameter `T` in the current scope
  --> src/geometry/tile.rs:23:41
   |
23 |     type Item = SmallString<[u8; 4 * T::DISPLAY_WIDTH]>;
   |                                         ^^^^^^^^^^^^^ associated item not found in `T`
   |
   = help: items from traits can only be used if the type parameter is bounded by the trait

Of interest is the fact that rustc doesn't complain at all about the use of the associated const in the for loop;有趣的是 rustc 根本不抱怨在 for 循环中使用相关的 const 。 just at the associated type definition.就在关联的类型定义处。

My suspicion is that this is a compiler bug: given that T is constrained by DisplayWidth , it should be available in the trait associated type definition context, but just isn't.我怀疑这是一个编译器错误:鉴于TDisplayWidth约束,它应该在特征关联类型定义上下文中可用,但不是。 However, I'm asking here before filing a bug report against rustc because I'm not 100% certain of that.但是,我在提交针对 rustc 的错误报告之前在这里询问,因为我不是 100% 确定这一点。

The workaround I'm using for the moment is simple: define a separate const and use that:我目前使用的解决方法很简单:定义一个单独的 const 并使用它:

pub const CHUNK_WIDTH: usize = 4;
    type Item = SmallString<[u8; 4 * CHUNK_WIDTH]>;

Is there a solution which would allow using DisplayWidth::DISPLAY_WIDTH , though?不过,是否有允许使用DisplayWidth::DISPLAY_WIDTH的解决方案?

This is a limitation of array length;这是数组长度的限制; it can't use any parameters or generic bounds even if they are scope.即使它们是 scope,它也不能使用任何参数或通用边界。 The issue came up during the stabilization of associated consts and the decision taken was to stabilize them without it.在稳定相关 const 的过程中出现了这个问题,因此决定在没有它的情况下稳定它们。

This limitation is specific to array length parameters, everything else works:此限制特定于数组长度参数,其他一切都有效:

pub trait Shape {
    const SIDES: usize;
}

pub trait SimpleIter {
    const Item: usize;    
}

impl<T: Shape> SimpleIter for T {
    // this is fine
    const Item: usize = T::SIDES;
}

The issue can being tracked here and here可以在此处此处跟踪问题

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

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