How to add field constraints to a trait

trait Decode
where 
    Self: Sized
{

    fn decode() -> Self;

    fn is_eof(&self) -> bool {
        self.offset >= self.length
    } 
}

(Playground)

trait Decode
where 
    Self: Sized
{

    fn decode() -> Self;

    fn offset(&self) -> i32;

    fn length(&self) -> i32;

    fn is_eof(&self) -> bool {
        self.offset() >= self.length()
    } 
}

IMHO I think trait shouldn't impose field definitions on its implementor

Traits can only require functions, associated types, and constants. There's no way to require a field be present on a type implementing a trait. @taufik-rama's solution of requiring a getter function is the way you can require something like a field.

Many languages that do allow fields in their interface definitions are actually using getter/setter functions, and the field is just syntactic sugar.

1 Like