How do declare a trait with a function that references an Associated constant

Is it even possible to make this compile such that when the send is called it injects const 10 into the array size?

trait Messenger{
    type SendT;
    type RecvT;
    const MAX_MSG_SIZE: usize = 5;

    fn send(&self, msg: Self::SendT) -> Result<[u8; Messenger::MAX_MSG_SIZE], std::io::Error>{  //// I would like the impl to 
        Ok([0; CltMessenger::MAX_MSG_SIZE])
    
    }
}

struct CltMessenger{

}
impl Messenger for CltMessenger{
    type SendT = String;
    type RecvT = String;
    const MAX_MSG_SIZE: usize = 10;
}


fn main(){
  let clt = CltMessenger{};
  clt.send("hi".to_string());
}

you need the highly experimental #![feature(generic_const_exprs)], then this should compile:

trait Messenger {
    type SendT;
    type RecvT;
    const MAX_MSG_SIZE: usize = 5;

    fn send(&self, msg: Self::SendT) -> Result<[u8; Self::MAX_MSG_SIZE], std::io::Error> {
        Ok([0; Self::MAX_MSG_SIZE])
    }
}

unfortunately, you cannot do it in stable rust. what does work in stable, is const generic argument, which does NOT have the same semantics, but depending on your use case, it might be a possible alternative:

trait Messenger<const MAX_MSG_SIZE: usize> {
    type SendT;
    type RecvT;
    fn send(&self, msg: Self::SendT) -> Result<[u8; MAX_MSG_SIZE], std::io::Error> {
        Ok([0; MAX_MSG_SIZE])
    }
}
struct CltMessenger {}
impl Messenger<10> for CltMessenger {
    type SendT = String;
    type RecvT = String;
}

fn main() {
    let clt = CltMessenger {};
    clt.send("hi".to_string());
}
4 Likes