Generic struct direct assignment

pub struct Field<T> 
{
    pub value: T,
}

Is it possible to achieve the next code?

let fld: Field<i32> = 42;

without an into() or new()?

let fld = Field { value: 42_i32 };

I guess the answer is "No" :slight_smile:

Rust has to implicit conversion like C++ [1]. We generally prefer a more explicit and easier to understand style.


  1. except lifetime variance and autoderef, if you want to consider those as conversions. ↩ī¸Ž

Yes, I like explicit. Experimenting with syntax and structures....

You can't construct through a plain assignment, but it's often possible to arrange for the conversion to be invisible when it happens in practice, by using generics and a conversion trait on relevant functions.

pub struct Field<T> {
    pub value: T,
}

// This defines the conversion, which we will later make sometimes-implicit.
impl<T> From<T> for Field<T> {
    fn from(value: T) -> Self {
        Self { value }
    }
}

pub struct Thing {
    field: Field<i32>,
}

impl Thing {
    pub fn new(field: impl Into<Field<i32>>) -> Self {
        Self {
            // Here we use the conversion defined above.
            field: field.into(),
        }
    }
}

fn main() {
    // No `Field` mentioned here!
    let thing = Thing::new(42);
}
1 Like

That is another nice one. It was more for creating (my 3d exercise project) 'persistent' database structs.
Something like:

struct CLIENT
{
    ID: Field<i32>,
    NAME: Field<String>,
    // etc.
}
let mut client = CLIENT::default();
client.ID = 42;

but probably easier is just

struct CLIENT
{
    ID: i32,
    NAME: String,
    // etc.
}

wrapping nullable fields into Option<>

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.