你怎么能够创建部分初始化的结构?

Pau*_*son 9 rust

在Rust中创建结构时,似乎很难在没有设置所有字段的情况下创建结构.例如,使用以下代码

struct Connection {
    url: String,
    stream: TcpStream
}
Run Code Online (Sandbox Code Playgroud)

如果url没有给出stream,你也无法设置.

// Compilation error asking for 'stream'
let m = Connection { url: "www.google.com".to_string() }; 
Run Code Online (Sandbox Code Playgroud)

你怎么能够创建这些引用,Option<None>直到以后的时间?

我发现的最好的是使用Default特征,但我宁愿不必创建TcpStream直到结构初始化的时间.我能用这样的东西做到这一点Box吗?

Jor*_*eña 10

有一两件事你可以做的是包裹TcpStream在一个Option,即Option<TcpStream>.当你第一次构造结构时,它将是None,并且当你初始化它时,你就可以了self.stream = Some(<initialize tcp stream>).无论您在何处使用TCPStream,都必须检查Some它是否已经初始化.如果你可以保证你的行为,那么你可以unwrap(),但最好还是做一个检查.

struct Connection {
    url: String,
    stream: Option<TcpStream>
}

impl Connection {
    pub fn new() -> Connection {
        Connection {
            url: "www.google.com".to_string(),
            stream: None,
        }
    }

    pub fn initialize_stream(&mut self) {
        self.stream = Some(TcpStream::connect("127.0.0.1:34254").unwrap());
    }

    pub fn method_that_uses_stream(&self) {
        if let Some(ref stream) = self.stream {
            // can use the stream here
        } else {
            println!("the stream hasn't been initialized yet");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这与Swift中的操作类似,以防您熟悉该语言.

  • 当然。那应该只是`ref stream`,我已经修复了它。它只是意味着获得了对 `Option` 中的流的引用,而不是完全移动值。有关更多信息,请查看 [Rust book](https://doc.rust-lang.org/book/second-edition/ch04-02-references-and-borrowing.html)。 (2认同)

She*_*ter 5

作为Jorge Israel Pe\xc3\xb1a\'s 答案的扩展,您可以使用构建器。构建器具有所有可选字段并生成不带Options 的最终值:

\n
use std::net::TcpStream;\n\nstruct ConnectionBuilder {\n    url: String,\n    stream: Option<TcpStream>,\n}\n\nimpl ConnectionBuilder {\n    fn new(url: impl Into<String>) -> Self {\n        Self {\n            url: url.into(),\n            stream: None,\n        }\n    }\n\n    fn stream(mut self, stream: TcpStream) -> Self {\n        self.stream = Some(stream);\n        self\n    }\n\n    fn build(self) -> Connection {\n        let url = self.url;\n        let stream = self\n            .stream\n            .expect("Perform actual error handling or default value");\n        Connection { url, stream }\n    }\n}\n\nstruct Connection {\n    url: String,\n    stream: TcpStream,\n}\n\nimpl Connection {\n    fn method_that_uses_stream(&self) {\n        // can use self.stream here\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

这意味着您不必在代码中乱七八糟地检查流是否已设置。

\n

也可以看看:

\n\n


归档时间:

查看次数:

5091 次

最近记录:

7 年,4 月 前