Is there a good way to get dynamic behavior with a generic type?
20:23 21 Feb 2025

I'm pretty new to Rust and am trying to learn how to think and design code the way that works best in Rust. (I have more experience in C++.) I recently came across a problem where I wanted to be able to handle a generic type dynamically, but I couldn't find a good solution. (See "Details" below.)

Is there a general approach for getting dynamic behavior out of generic types in Rust? Or would the suggestion be to not do this at all? If so, what would be the better approach?

Details

I was recently making an Array3D struct in Rust. I was attempting to implement Display for this struct when I ran into an issue. Since the array holds a generic type, I don't know how to display the elements. Can I just use t.to_string()? Will I have to use format!("{:?}", t)? Or something else?

My first thought was to do separate implementations based on the traits that the generic implements. For example, something like this:

impl Display for Array3D {
    // implementation
}

impl Display for Array3D {
    // implementation
}

But then I discovered that this isn't possible in Rust. I understand why: some types implement both Debug and Display, so the compiler wouldn't know which implementation to use. From what I understand, there are plans to eventually use specialization to make something like this possible. (Not exactly like this, but similar enough.)

I found a solution for this specific example. I created a get_pretty_string() method that takes an elem_to_string function as one of its parameters. The downside of this method is that I have to pass an extra parameter each time I want to display my Array3D.

/// Returns the pretty string representation of this [`Array3D`].
pub fn get_pretty_string String>(
    &self,
    elem_width: usize,
    elem_align: Alignment,
    inverse_y: bool,
    elem_to_string: F,
) -> String {
    /// implementation
}

So I found a solution in this specific case, but is there a generally good approach to take when dealing with this kind of scenario?

generics rust dynamic