Type alias with trait bound

Hey!

Beginner question here, sorry not sure what keyword to use to search for help on this.

I have the following type alias:

type PacketWriter<T> where std::io::Cursor<T>: std::io::Write = std::io::Cursor<T>;

And a function

    fn write_something<T>(c: &mut PacketWriter<T>) -> Result<(), std::io::Error> {
        let mut buf = [0u8; 16];
        c.write_all(&buf).expect();

        return Ok(());
    }

But compilation fails saying the Write trait is not satisfied.

    |
272 |           c.write_all(buf).expect();
    |             ^^^^^^^^^ method cannot be called on `&mut std::io::Cursor<T>` due to unsatisfied trait bounds
    |
    = note: the following trait bounds were not satisfied:
            `std::io::Cursor<T>: std::io::Write`
            which is required by `&mut std::io::Cursor<T>: std::io::Write`

Any idea how I can fix the type alias to add the trait bound? (I thought the where std::io::Cursor<T>: std::io::Write would do the trick, but apparently it doesn't.

Thanks!

Edit: I know I can fix it by adding where std::io::Cursor<T>: std::io::Write at the end of the function declaration, but I am trying to avoid to have to keep writing this for every function.

You can't avoid writing the bound on the function, because you need a constraint for T. You can't just pass any type there and have the function work.

You might be able to use a trait to make the bound simpler, but you'll still need some sort of bound on T as long as you're designing things this way.

If you're okay getting rid of the type alias, you could move the bounds into a struct

Playground

use std::io::prelude::*;

struct PacketWriter<T>(std::io::Cursor<T>);

impl<T> PacketWriter<T> where std::io::Cursor<T>: std::io::Write {
    fn write_something(&mut self) -> Result<(), std::io::Error> {
        let mut buf = [0u8; 16];
        self.0.write_all(&buf).unwrap();
    
        return Ok(());
    }
}
1 Like

I see. Thanks @semicoleon . I thought I could specify the bounds in the type alias. What you suggested would work I guess! Thanks!

Hopefully someday bounds on aliases will be supported. You can read the why's and challenges here and in the issues linked within.

(The issue is technically about the warning you get when you do put a bound on an alias.)

Related: Implied bounds.

2 Likes

Thanks!

(The issue is technically about the warning you get when you do put a bound on an alias.)

Yeah... I conveniently ignored the warning hoping things will be fine :smiley:

1 Like