How do I make a struct with custom values?

If I want to create, lets say, multiple boxes.
This struct Box has width, height, and color as fields.

I want to create a small Box through the Box struct as you would create any other struct, but with the name of small (for small box) (let box: Box = Box::new("small", orange)). Could even use ints, if that's easier; new(1) = small.
The different size boxes, small, medium, large, would each have their own default values. F.e. small; width/height = 5, large; width/height = 15. And the color would be set through the given parameter.

How can I achieve this?

You can receive a size parameter in the new method and create a new Box with the desired dimensions.

I advise you don't call it Box; that's a fundamental Rust type.

You could have an enum for the standard sizes.

2 Likes

If you have a small number of "default styles" you can just create a new constructor for each

struct Box {
    width: usize,
    height: usize,
    color: String,
}

impl Box {
    fn small(color: String) -> Self {
        Self {
            width: 5,
            height: 5,
            color,
        }
    }

    fn large(color: String) -> Self {
        Self {
            width: 15,
            height: 15,
            color,
        }
    }
}

If there are other times you want to be able to refer to the "default styles" then an enum is probably a better fit.

You could also technically use a trait and a type parameter, but that feels like overkill for this case.

I will also second @quinedot's note that you should probably avoid calling it Box

1 Like

Would you say using an enum is a workaround using a trait? Or is it basically the same as using a trait on smaller scale?

A trait is good if you have lots of options and/or an external crate may want to add its own defaults.

An enum is better if you have a known number of options, and don't need to be able to extend it from another crate.

2 Likes

Ok, thanks ^^

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.