pub trait FromRow: Sized {
// Required method
fn from_row(row: Row) -> Result<Self>;
}Expand description
Converts a query Row into a Rust data structure.
§Example
use google_cloud_spanner::Error;
use google_cloud_spanner::result::{FromRow, Row};
struct UserRecord {
id: String,
age: i64,
nickname: Option<String>,
}
impl FromRow for UserRecord {
fn from_row(mut row: Row) -> Result<Self, Error> {
Ok(Self {
id: row.take("id")?,
age: row.take("age")?,
nickname: row.take("nickname")?,
})
}
}
// Implementing `TryFrom<Row>` is optional, and enables standard `row.try_into()` conversion:
impl TryFrom<Row> for UserRecord {
type Error = Error;
fn try_from(row: Row) -> Result<Self, Self::Error> {
Self::from_row(row)
}
}
// A row can be converted into the record using `Row::into_record`:
let user: UserRecord = row.into_record()?;
println!("User: {}, age: {}", user.id, user.age);This trait is designed for zero-copy row consumption. The implementing method
takes ownership of Row, allowing callers to move heap-allocated types
(such as String, Vec<T>, and Vec<u8>) using Row::take
without cloning.
FromRow is also implemented for Row (identity) and standard tuples up to
12 elements (positional indexing). Single-column scalar queries (such as
SELECT COUNT(*)) can be read using a 1-tuple (T,) (e.g. (i64,)).
§Example: Tuples and Scalar Queries
Standard tuples up to 12 elements implement FromRow using positional indexing:
// Multi-column positional query:
let (name, age): (String, i64) = row.into_record()?;
println!("Name: {name}, Age: {age}");
// Single-column scalar query (e.g. `SELECT COUNT(*)`):
let (count,): (i64,) = row.into_record()?;
println!("Count: {count}");Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".