I have a struct Message
as follows:
struct Message<'a> {
message_type: String,
data: &'a [u8],
}
The socketcan library has the CANFrame::data
method that returns a &[u8]
.
I would not like to copy this into a vector, as I'd like it to all remain in the Message
object on the stack, but I want to move the data from one to another.
match socket.read_frame() {
Ok(frame) => {
let message = Message {
message_type: format!("{}", frame.id()),
data: frame.data().clone(),
};
However, the result frame.data()
does not live long enough as the frame's scope is (and should be) fairly short:
error[E0597]: `frame` does not live long enough
--> src/main.rs:27:31
|
27 | data: frame.data().clone(),
| ^^^^^ borrowed value does not live long enough
...
39 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...
I know that the slice is only going to be at most 8 elements, as that's the limitation of the CAN protocol. What I really want is a struct that holds a [u8]
as well as a usize
(or u8
would also be valid) and thus can be converted to a slice with the correct size.
I'm just trying to figure out the idiomatic way to move (in the English "move" sense, as I may not want to use move semantics here -- not sure) the data from the CANFrame
to the Message
.