Type of a serialport #118
-
If I open a serial port with
the return type is a I want to implement a struct to store (many things, and) the opened port for later reading/writing. The structure will look like :
But how can I initialize the I would do this :
but the SerialPort trait doesn't implement new (which makes sense). And I can not initialize the structure without initializing the port member. I could store a This question is probably purely "rust related", but I just can't figure the solution out... Maybe it could be worth adding this to the Readme.md Usage chapter, because normally you don't open a serial port, read or write to it and then get out of scope. Thanks for your kind help. David. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Since serialport-rs uses a RAII philosophy, if you have access to a port it is also open. I think this results in the issue you describe, so I might suggest something like: port: Option<Box<dyn SerialPort>> When you initialize your structure, the port will be This does create some boilerplate when reading/writing to the port, since you need to be checking if the port is The other option, of course, is simply to open/create the port when you create your structure. |
Beta Was this translation helpful? Give feedback.
-
Thank you so much for your quick and explicit answer. I am having such a hard time getting used to rust... And it is clearly not about the syntax ! |
Beta Was this translation helpful? Give feedback.
-
Thank you for your answer @mlsvrts! |
Beta Was this translation helpful? Give feedback.
Since serialport-rs uses a RAII philosophy, if you have access to a port it is also open.
I think this results in the issue you describe, so I might suggest something like:
When you initialize your structure, the port will be
None
; when you acquire/open a port it will beSome(Box<dyn SerialPort>)
.This does create some boilerplate when reading/writing to the port, since you need to be checking if the port is
Some
-- but I think this is conceptually the same as needing to check that a port is 'open'.The other option, of course, is simply to open/create the port when you create your structure.