In a general sense, no; Rust has no private enum constructors. Enumerations are purely public things.
Structures, however, are not, and so you can combine them to make options purely implementation details:
// This type isn’t made public anywhere, so it’s hidden.
enum ShapeInner {
// Oh, and let’s use struct variants ’cos they’re cool.
Circle {
x: i32,
y: i32,
radius: f64,
},
Rectangle {
x1: i32,
y1: i32,
x2: i32,
y2: i32,
},
}
// Struct fields are private by default, so this is hidden.
pub struct Shape(ShapeInner);
impl Shape {
pub fn new_circle(radius: f64) -> Shape {
Shape(Circle { x: 0, y: 0, radius: radius })
}
pub fn new_rectangle(width: i32, height: i32) -> Shape {
Shape(Rectangle { x1: 0, y1: 0, x2: width, y2: height })
}
// "match self.0 { Circle { .. } => …, … }", &c.
}
I would advise against this as a general practice.
source
share