So I have a struct with a new
method that makes a HTTP request and returns part of the response, which should deserialize into the struct that this method is for. The problem I'm having is that the part of the response I need is contained within a Vec<>
in the response and using .first()
gives a reference to it.
I tried dereferencing it, but my struct needs to have the Copy
trait. So then I derived that, but my struct contains a field with a Vec<>
type, and that needs to have the Copy
trait. I learned about the error I was getting a bit and found out that references always have the Copy
trait, so I should be able to just make my field &'a Vec<>
. At this point I'm getting into named lifetimes territory, which I'm not very familiar with, being fairly new to Rust. It still doesn't work though, because:
error[E0277]: the trait bound `&'a Vec<f32>: Deserialize<'_>` is not satisfied
--> src/embeddings.rs:26:14
|
26 | pub vec: &'a Vec<f32>,
| ^^^^^^^^^^^^ the trait `Deserialize<'_>` is not implemented for `&'a Vec<f32>`
|
And now I'm stuck. Here's hopefully enough of my code to find a solution:
#[derive(Deserialize)]
struct NewEmbeddingRequestResponse<'a> {
data: Vec<Embedding<'a>>,
}
#[derive(Deserialize, Clone, Copy)]
pub struct Embedding<'a> {
/* ... */
pub vec: &'a Vec<f32>,
}
impl<'a> Embedding<'a> {
pub async fn new(/* ... */) -> Result<Embedding<'a>, reqwest::Error> {
/* ... */
let response: NewEmbeddingRequestResponse = client.post(/* ... */)
/* ... */
.send().await?.json().await?;
let embedding = *response.data.first().unwrap();
Ok(embedding)
}
}