Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Coercion

This section discusses Rust's Into trait, which facilitates type conversion. FieldX supports this trait through the <a name="a001"></a>into argument, enabling automatic conversion of a value into the field type when setting its value:

use fieldx::fxstruct;

#[fxstruct(get, builder)]
struct Book {
    title:  String,
    author: String,
    year:   u32,
    #[fieldx(get(copy), set)]
    available: u16,
    #[fieldx(set("place_into", into))]
    location: String,
}

let mut book = Book::builder()
    .title("The Hitchhiker's Guide to the Galaxy".to_string())
    .author("Douglas Adams".to_string())
    .year(1979)
    .available(1)
    .location("R12.S2".to_string()) // Row 12, Section 2
    .build()
    .expect("Failed to create book");

book.place_into("R12.S3");
assert_eq!(book.location(), "R12.S3");

Compare this to the example from the Setters section:

book.place_into("R12.S3".to_string());

Although, for better readability, a method from another trait – Display – is used, the concept remains the same: the into argument allows you to set a field value using a type that implements the Into trait for the field type. Since &str implements Into<String>, one could replace the to_string() method call with the into() method interchangeably, preserving the semantics of the code.

Finally, why is this section titled "Coercion"? The intent is to highlight the distinction between the explicit use of the Into trait by manually invoking the into() method and the implicit coercion performed within the methods generated by FieldX for you.