#Idiomatic way to add constraints to structs

4 messages · Page 1 of 1 (latest)

sand acorn
#

Very basic rust question:
Let's say I'm modeling a configuration in Rust using a struct. What's the best way to apply "parse don't validate"?
For example (Syntax isn't correct, but this is the idea):

struct Config = {
 tmp: Number between 0 and 1,
 voy: Word that begins with "Hello",
 duration: Duration value that is between 5 and 10
}
untold zenith
#

Use types that can only represent the values you want. The first one is easy, that's just bool, the rest you could make yourself. You would have the constructor of the type check for correctness.

fierce sail
#

You could define a type BeginsWithHello{ rest: String } or the more general thing is 'refinement types' for these constrained value things

#

Generally you don't want these arbitrary predicates, but good ones that model your proble. constrain how they can be used simplifying design