ligma
October 9, 2020, 11:47am
1
I have this enum
enum Message {
NewJob(Job),
Terminate,
}
It basically resembles Option where T is Jobs, Some is NewJob and Terminate is None. The main thing it doesn't have is all the methods provided by Option. So, can I have like an alias for this enum to Option, so that I don't need to reimplement the required methods of Option?
What about type Message = Option<Job>
?
ligma
October 9, 2020, 12:10pm
3
But, still I've to use Some and None as enum values. I wanted to use NewJob(job) instead of Some(job) and Terminate instead of None
tesuji
October 9, 2020, 12:51pm
4
Which methods in Option that you want to use ?
Considering impl Deref and / or DerefMut with Target=Option ?
Then adding / overriding your own methods
Finn
October 9, 2020, 1:23pm
5
The desired aliases could be achieved this way:
type Message = Option<Job>;
use Option::Some as NewJob;
use Option::None as Terminate;
ligma
October 9, 2020, 1:54pm
7
Actually for my case, this is simple enough for me. I don't need to override any methods, just use them as is
Finn
October 9, 2020, 1:56pm
8
But I would recommend this more stringent construction:
mod message_module {
pub struct Message {
pub job: Option<Job>
}
impl Message {
pub fn new_job(job: Job) -> Self {Self{job: Some(job)}}
pub fn terminated() -> Self {Self{job: None}}
}
}
Further strictness can be achieved by making job
private and redirecting the needed methods to the inner option. Furthermore you may want to add this:
pub enum JobOption {NewJob(Job), Terminated}
impl Message {
pub fn job(self) -> JobOption {
match self.job {
Some(job) => JobOption::NewJob(job),
None => JobOption::Terminated
}
}
}
Depending on which level of rigor is desired.
1 Like
Just out of curiosity, what methods are you looking for?
ligma
October 9, 2020, 3:07pm
10
for now, the map() and take() method
system
Closed
January 7, 2021, 3:07pm
11
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.