Read Rust

Tag: traits


I ran into this a little while ago and thought it would be helpful to share a possible solution.

Imagine you have an enum that describes a set of possible branches, for each branch there is a type associated with it that you want to run through a function, for this example– serialize.

Life is good. Then you realize that you actually needed to format these types in two different ways, one with to_writer and the other with to_writer_pretty. You could make a write and write_pretty function, but that feels dirty. The only thing that would be different in each implementation is the function from serde_json.


This is a fairly basic Rust syntax issue that I’ve run into several times. Based on unknowable runtime conditions, I will return one of several different return types from the same function. Also, this return type must use methods from two traits. How can I express this in Rust?


View all tags