How to add a constraint to a field of a struct for instantiation?

Viewed 183

I have a simple struct with one string field:

pub struct Chunk {
    signature: String
}

This string field cannot be just any string, there are bunch of constraints that it needs to satisfy (and if string passed to constructor does not satisfy these constraints, construction of struct should fail).

In object-oriented languages like C++, I would make the explicit constructor that does the needed checks, what is the correct way to do this in Rust?

I came up with this code:

impl Chunk {
    pub fn new(s: String) -> Option<Chunk> {
        if constraints_fail {
            None
        } else {
            Some(Chunk{signature: s})
        }
    }
}

I'm not sure if this is a correct approach, since technically the struct can still be instantiated with invalid string parameter without ever calling this function.

1 Answers

Your struct contains a private field, therefore it cannot be instantiated from outside. This is what you get if you try:

error[E0451]: field `signature` of struct `Chunk` is private
 --> src/main.rs:8:24
  |
8 |     let _ = Chunk { signature: "xxx".to_owned() };
  |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^ private field

You don't need to do anything else - just keep the signature field private.

Related