TryFromContents

Trait TryFromContents 

Source
pub trait TryFromContents: Sized {
    // Required method
    fn try_from_contents<'a, I: Iterator<Item = &'a Content>>(
        contents: I,
    ) -> Result<Self, Error>;
}
Expand description

Conversion trait for parsing structured data from response contents.

This is the backbone of type-safe responses. While you can implement it directly, most users should prefer the automatic implementation provided by serde.

§Serde Default

With the serde feature enabled, any serde::Deserialize type automatically implements this trait by expecting JSON-formatted responses:

#[derive(Deserialize)]
struct MyResponse {
    answer: String,
    confidence: f32,
}

// Automatically implements TryFromContents!

§Manual Implementation

Implement this directly for non-JSON formats or custom parsing logic:

use google_ai_rs::{Data, Part, Content, Error, error::ServiceError};

struct TextLength(usize);

impl TryFromContents for TextLength {
    fn try_from_contents<'a, I: Iterator<Item = &'a Content>>(contents: I) -> Result<Self, Error> {
        // Extract text from first content part
        let text = contents.into_iter()
             .flat_map(|c| c.parts.iter())
             .find_map(|p| match p {
                   Part { data: Some(Data::Text(text)) } => {
                       Some(text)
                   }
                   _ => None
             })
            .ok_or(Error::Service(ServiceError::InvalidResponse("Empty response".into())))?;
         
        Ok(TextLength(text.len()))
    }
}

Required Methods§

Source

fn try_from_contents<'a, I: Iterator<Item = &'a Content>>( contents: I, ) -> Result<Self, Error>

Parses the response contents into a concrete type.

Implementations should:

  1. Extract relevant data from the content parts
  2. Handle error cases (missing data, invalid formats)
  3. Return the parsed value or appropriate error

The default serde implementation expects exactly one JSON-formatted text part.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§