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> {
let addr = format!("{}:{}", ip, port);
let conn = TcpStream::connect(&addr)?;
Ok(FistClient { addr, conn })
}
}
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.