Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rust 我可以创建私有枚举构造函数吗?_Rust - Fatal编程技术网

Rust 我可以创建私有枚举构造函数吗?

Rust 我可以创建私有枚举构造函数吗?,rust,Rust,在Haskell中,我可以做类似的事情(示例改编自) 这将允许我只公开Shape类型和newCircle和newRectangle函数 锈病是否与此相当?在一般意义上,没有;Rust没有私有枚举构造函数。枚举是纯粹的公共事物 但是,结构不是这样的,因此您可以将它们组合起来,使变体纯粹成为一个实现细节: // This type isn’t made public anywhere, so it’s hidden. enum ShapeInner { // Oh, and let’s us

在Haskell中,我可以做类似的事情(示例改编自)

这将允许我只公开
Shape
类型和
newCircle
newRectangle
函数


锈病是否与此相当?

在一般意义上,没有;Rust没有私有枚举构造函数。枚举是纯粹的公共事物

但是,结构不是这样的,因此您可以将它们组合起来,使变体纯粹成为一个实现细节:

// 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.
}

但是,作为一般做法,我建议不要这样做。

我投票将这个问题作为离题题来结束,因为它是关于检查防锈文件和路线图的。您能提供一个到文件和路线图的链接吗?作为一个新用户,我还没有发现所有的文档。一、 正如我想象的那样,许多新用户正在阅读这本书,当这本书不够详细时,我会在别处寻找答案。@Chiron我认为核心问题是一个好问题,标题只需要稍微调整一下,成为一个具体的问题(就像正文一样),而不是一个未来计划问题。@NJPUL,这个和那个。更大的未来计划通常可以在@Shepmaster中找到,谢谢链接。我在网站上很容易找到前三个,但我不知道RFC。你为什么反对呢?因为它看起来很像一个设计模式?@ker:“设计模式”没有内在的邪恶。这仅仅是因为,一般来说,这不会是惯用的锈病,尽管可能有某些情况非常适合这样做(不过,我想不出任何现成的例子)。
// 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.
}