如何在具有空值的结构中设置字段?

How to set a field in a struct with an empty value?

我正在编写一个 TCP 客户端并且在我的客户端结构中有一个 conn 字段。我的客户端实现了两种方法 new 来实例化结构并连接以打开与服务器的连接并将其设置为 conn 字段的值

pub struct FistClient {
    addr: String,
    conn: TcpStream,
}

impl FistClient {
    pub fn new(ip: &str, port: &str) -> Self {
        FistClient {
            addr: String::from(ip) + ":" + &String::from(port),
            // conn: <some-defaullt-value>,
        }
    }

    pub fn connect(&mut self, ip: &str, port: &str) {
        let res = TcpStream::connect(&self.addr);
        match res {
            Ok(c) => self.conn = c,
            Err(_) => panic!(),
        }
    }
}

我想将新方法中的 conn 字段设置为某个默认值。在 Go 中,我可以做类似 conn: nil 的事情,但它在这里不起作用。我也尝试了 Default::default(),但是 TCPStream 没有实现该特性,我应该如何将其设置为默认值?

Rust 中没有null(也没有空指针异常,Rust 是为安全而设计的)。

你必须

1) 使用 option(即 Option<TcpStream> 类型的字段)

2) 或更好:return a result 构建结构时

在这里,最好的选择可能是从函数内部连接 ​​returning a Result<FistClient>,这样您就不必检查您的结构是否具有有效流。

我会这样做:

pub struct FistClient {
    addr: String,
    conn: TcpStream,
}

impl FistClient {
    pub fn new(ip: &str, port: &str) -> Result<Self> {
        let addr = format!("{}:{}", ip, port);
        let conn = TcpStream::connect(&addr)?;
        Ok(FistClient { addr, conn })
    }
}

旁注:最好不要通过调用 panic 来构建应用程序,即使您认为自己只是在构建草稿。 Handle errors 相反。

如果您想保留此呼叫模式,您需要将类型更改为 Option<TCPStream>Option 表示可能缺少具有两个枚举变体的值(即 null):Some(_)None.

设置好后,您可以通过调用 as_mut 检索 Option<&mut T> 轻松检索对内部成员的可变引用。

在 Rust 中,null 的概念是用 Option 建模的。您给字段类型 Option<TcpStream> 以指示它可能不存在 (None),或者是一个有效值 (Some(TcpStream))。

pub struct FistClient {
    addr: String,
    conn: Option<TcpStream>,
}

impl FistClient {
    pub fn new(ip: &str, port: &str) -> Self {
        FistClient {
            addr: String::from(ip) + ":" + &String::from(port),
            conn: None,
        }
    }

    pub fn connect(&mut self, ip: &str, port: &str) {
        let res = TcpStream::connect(&self.addr);
        match res {
            Ok(c) => self.conn = Some(c),
            Err(_) => panic!(),
        }
    }
}