Rust无法在特征函数中使用特征const

时间:2019-12-27 22:07:12

标签: rust

因此,我尝试定义一个具有常量的特征,并在函数“标头”中使用该常量,但它给我一个错误,即没有这样的关联常量。

代码:

trait SizedBuffer {   
    const SIZE: usize;
    fn read(&mut self, buf: &mut [u8; Self::SIZE]);
    fn write(&mut self, buf: &[u8; Self::SIZE]);
}

fn main() {
    println!("It compiled!");
}

预期结果:

It compiled!

相反,我得到了:

error[E0599]: no associated item named `SIZE` found for type `Self` in the current scope
 --> src/main.rs:3:45
  |
3 |     fn read(&mut self, buf: &mut [u8; Self::SIZE]);
  |                                             ^^^^ associated item not found in `Self`
  |
  = help: items from traits can only be used if the type parameter is bounded by the trait
help: the following trait defines an item `SIZE`, perhaps you need to restrict type parameter `Self` with it:
  |
1 | Self: SizedBuffer
  |

error[E0599]: no associated item named `SIZE` found for type `Self` in the current scope
 --> src/main.rs:4:42
  |
4 |     fn write(&mut self, buf: &[u8; Self::SIZE]);
  |                                          ^^^^ associated item not found in `Self`
  |
  = help: items from traits can only be used if the type parameter is bounded by the trait
help: the following trait defines an item `SIZE`, perhaps you need to restrict type parameter `Self` with it:
  |
1 | Self: SizedBuffer
  |

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0599`.
error: could not compile `trait_const`.

To learn more, run the command again with --verbose.

0 个答案:

没有答案
相关问题