I have a very simple case where I have some function that takes a Option<Vec>, it then needs to look at that option, and if it is a None, then have a empty byte string, but if it is a Some, then call a function that does some transofmration of it's input.
Sketched out, it looks like this:
pub fn transform(ad: &[u8]) -> Vec<u8> {
ad.to_vec()
}
pub fn func(plaintext: Option<Vec<u8>>) {
let out = "".as_bytes();
if plaintext != None {
let out = transform(&plaintext.unwrap());
}
}
Doing the unwrapping and the if like this is really ugly though,and I would much like to do this in a safer way, maybe with pattern matching:
pub fn transform(ad: &[u8]) -> Vec<u8> {
ad.to_vec()
}
pub fn func(plaintext: Option<Vec<u8>>) {
let out = match plaintext {
Some(x) => &transform(&x),
None => "".as_bytes()
};
}
But this gives the error:
|
16 | let out = match plaintext {
| --- borrow later stored here
17 | Some(x) => &return_smth(&x),
| ^^^^^^^^^^^^^^-
| | |
| | temporary value is freed at the end of this statement
| creates a temporary which is freed while still in use
|
= note: consider using a `let` binding to create a longer lived value
I am unsure about which value that is being talked about here. How do I call my function, and get a slice returned?