如何在具有空值的结构中设置字段? [英] How to set a field in a struct with an empty value?

查看:45
本文介绍了如何在具有空值的结构中设置字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

pub struct FistClient {地址:字符串,连接:TcpStream,}impl FistClient {pub fn new(ip: &str, port: &str) ->自己 {FistClient {地址:String::from(ip) + ":" + &String::from(port),//conn: <some-defaullt-value>,}}pub fn 连接(&mut self, ip: &str, port: &str) {让 res = TcpStream::connect(&self.addr);匹配资源{好的(c) =>self.conn = c,错误(_)=>恐慌!(),}}}

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

解决方案

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

你必须要么

1) 使用 option(即Option)

类型的字段

2) 或更好:返回 result构建结构时

在这里,最好的选择可能是从返回 Result 的函数内部进行连接,这样您就不必检查您的结构是否具有有效的流.

我会做这样的事情:

pub struct FistClient {地址:字符串,连接:TcpStream,}impl FistClient {pub fn new(ip: &str, port: &str) ->结果<自己>{好的(FistClient {地址:格式!("{}:{}", ip, port),conn: TcpStream::connect(&self.addr)?,})}}

旁注:最好不要通过调用 panic 来构建应用程序,即使您认为自己只是在构建一个脏草稿.处理错误.

Newbie rustacean here. I am writing a TCP client and have a conn field in my client struct. My client implements two methods new to instantiate the struct and connect to open a connection to the server and set that as the value of the conn field

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!(),
        }
    }
}

I want to set the conn field in the new method to some default value. In Go I can do something like conn: nil but it doesn't work here. I tried Default::default() too but that trait isn't implemented for TCPStream how should I set it to a default value?

解决方案

There's no null in Rust (and no Null Pointer Exception, Rust is designed for safety).

You must either

1) use an option (i.e. a field of type Option<TcpStream>)

2) or better: return a result when building the struct

Here, the best option would probably be to connect from inside a function returning a Result<FistClient>, so that you don't have to check whether your struct has a valid stream.

I would do something like this:

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

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

Side note: It's really preferable to not build your applications with calls to panic, even when you think you're just building a dirty draft. Handle errors instead.

这篇关于如何在具有空值的结构中设置字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆