我可以创建私有枚举构造函数吗?
Can I create private enum constructors?
在 Haskell 中我可以做这样的事情(示例改编自 Learn You A Haskell)
module Shapes (
Shape,
newCircle,
newRectangle,
... -- other functions for manipulating the shapes
)
data Shape = Circle Int Int Float -- x, y, radius
| Rectangle Int Int Int Int -- x1, y1, x2, y2
newCircle :: Float -> Shape
newCircle r = Circle 0 0 r
newRectangle :: Int -> Int -> Shape
newRectangle w h = Rectangle 0 0 w h
... -- other functions for manipulating the shapes
这将允许我只公开 Shape
类型以及 newCircle
和 newRectangle
函数。
Rust 有这方面的等效项吗?
一般意义上,没有; Rust 没有私有枚举构造函数。枚举纯粹是 public 东西。
然而,结构不是那样的,因此您可以将它们组合起来,使变体成为纯粹的实现细节:
// 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.
}
但是,我建议不要将此作为一般做法。
在 Haskell 中我可以做这样的事情(示例改编自 Learn You A Haskell)
module Shapes (
Shape,
newCircle,
newRectangle,
... -- other functions for manipulating the shapes
)
data Shape = Circle Int Int Float -- x, y, radius
| Rectangle Int Int Int Int -- x1, y1, x2, y2
newCircle :: Float -> Shape
newCircle r = Circle 0 0 r
newRectangle :: Int -> Int -> Shape
newRectangle w h = Rectangle 0 0 w h
... -- other functions for manipulating the shapes
这将允许我只公开 Shape
类型以及 newCircle
和 newRectangle
函数。
Rust 有这方面的等效项吗?
一般意义上,没有; Rust 没有私有枚举构造函数。枚举纯粹是 public 东西。
然而,结构不是那样的,因此您可以将它们组合起来,使变体成为纯粹的实现细节:
// 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.
}
但是,我建议不要将此作为一般做法。