Using an interface to determine buffer


New please be gentle.

Trying to get to grips with interfaces and struggling to solve this. Just want the first generic to determine the size of the buffer.

#[derive(Debug, Clone)]
pub struct BufferedGraphicMode<D> 
    D: DisplayDefinition
    buffer: [u16; D::COLS * D::ROWS as usize],
    min_x: u16,
    max_x: u16,
    min_y: u16,
    max_y: u16,

It says

error: generic parameters may not be used in const operations
  --> gc9a01-rs/src/mode/buffered_graphic/
10 |     buffer: [u16; D::COLS * D::ROWS as usize],
   |                   ^^^^^^^ cannot perform const operation using `D`
   = note: type parameters may not be used in const expressions
   = help: add `#![feature(generic_const_exprs)]` to allow generic const expressions

But I am struggling looking at the example on help

As a bonus question where to I get help for this. I can see what it does (I think). Creates a mututable buffer of size 2 bytes + ???????

type Buffer: AsMut<[u16]> + NewZeroed;

but done really understand how, specifically the + sign.

Here is the imp

pub trait NewZeroed {
    /// Creates a new value with its memory set to zero
    fn new_zeroed() -> Self;

impl<const N: usize> NewZeroed for [u16; N] {
    fn new_zeroed() -> Self {
        [0u16; N]

Computation through associated const generics is quite limited in Rust, and needs the nightly feature. Rust Playground

Update: it may be common to use generic-array — data structures in Rust // as a stable solution (disclaimation: I have no experience with it)


This doesn't create anything. It's an associated type declaration from inside a trait, telling you that implementations of this trait must define a type Buffer, which must implement the two traits AsMut<[u16]> and NewZeroed. You've found the definition of NewZeroed - one method, fn new_zeroed() -> Self, to create a new value with its memory set to zero. AsMut<T> is also a trait with one method, fn as_mut(&mut self) -> &mut T that allows you to get a mutable (exclusive) reference to itself as the type T.

In this case, because it's AsMut<[u16]>, there's guaranteed to be a method fn as_mut(&mut self) -> &mut [u16] for whatever type you choose for Buffer in an implementation of this trait.


Thanks, associated type was what I was after. Once I have the right term hopefully plain sailing. Struggle with written word sometimes, always wish I had an education.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.