Result has no method called “unwrap()”?

If you read the documentation for Result::unwrap, you’ll note that it’s under a little section called: impl<T, E> Result<T, E> where E: Debug This means the methods in that section only exist so long as the given constraints are satisfied. The only reason unwrap wouldn’t exist is that Error doesn’t implement Debug.

Should Cargo.lock be committed when the crate is both a rust library and an executable?

Yes, crates that depend on your library will ignore your Cargo.lock. The Cargo FAQ provides more details: Why do binaries have Cargo.lock in version control, but not libraries? The purpose of a Cargo.lock is to describe the state of the world at the time of a successful build. It is then used to provide deterministic … Read more

Why is type conversion from u64 to usize allowed using `as` but not `From`?

as casts are fundamentally different from From conversions. From conversions are “simple and safe” whereas as casts are purely “safe”. When considering numeric types, From conversions exist only when the output is guaranteed to be the same, i.e. there is no loss of information (no truncation or flooring or loss of precision). as casts, however, … Read more

How do I find the path to the home directory for Linux?

From the home crate. The definition of home_dir provided by the standard library is incorrect because it relies on the $HOME environment variable which has basically no meaning in Windows. This causes surprising situations where a Rust program will behave differently depending on whether it is run under a Unix emulation environment. Neither Cargo nor … Read more

How would you stream output from a Process?

Although the accepted answer is correct, it doesn’t cover the non-trivial case. To stream output and handle it manually, use Stdio::piped() and manually handle the .stdout property on the child returned from calling spawn, like this: use std::process::{Command, Stdio}; use std::path::Path; use std::io::{BufReader, BufRead}; pub fn exec_stream<P: AsRef<Path>>(binary: P, args: Vec<&’static str>) { let mut … Read more

How can I unpack (destructure) elements from a vector?

It seems what you need is “slice patterns”: fn main() { let line = “127.0.0.1 1000 what!?”; let v = line.split_whitespace().take(3).collect::<Vec<&str>>(); if let [ip, port, msg] = &v[..] { println!(“{}:{} says ‘{}'”, ip, port, msg); } } Playground link Note the if let instead of plain let. Slice patterns are refutable, so we need to … Read more

How to read a specific number of bytes from a stream?

Since Rust 1.6, Read::read_exact can be used to do this. If bytes_to_read is the number of bytes you need to read, possibly determined at runtime, and reader is the stream to read from: let mut buf = vec![0u8; bytes_to_read]; reader.read_exact(&mut buf)?; The part that wasn’t clear to me from the read_exact documentation was that the … Read more

techhipbettruvabetnorabahisbahis forumuedusedueduseduedusedusedusedusedusedus