What is the correct way to return an Iterator (or any other trait)?

I’ve found it useful to let the compiler guide me: fn to_words(text: &str) { // Note no return type text.split(‘ ‘) } Compiling gives: error[E0308]: mismatched types –> src/lib.rs:5:5 | 5 | text.split(‘ ‘) | ^^^^^^^^^^^^^^^ expected (), found struct `std::str::Split` | = note: expected type `()` found type `std::str::Split<‘_, char>` help: try adding a … Read more

When does a closure implement Fn, FnMut and FnOnce?

The traits each represent more and more restrictive properties about closures/functions, indicated by the signatures of their call_… method, and particularly the type of self: FnOnce (self) are functions that can be called once FnMut (&mut self) are functions that can be called if they have &mut access to their environment Fn (&self) are functions … Read more

How can I build multiple binaries with Cargo?

You can specify multiple binaries using [[bin]], as mentioned here: [[bin]] name = “daemon” path = “src/daemon/bin/main.rs” [[bin]] name = “client” path = “src/client/bin/main.rs” Tip: If you instead put these files in src/bin/daemon.rs and src/bin/client.rs, you’ll get two executables named daemon and client as Cargo compiles all files in src/bin into executables with the same … Read more

What is the difference between Copy and Clone?

Clone is designed for arbitrary duplications: a Clone implementation for a type T can do arbitrarily complicated operations required to create a new T. It is a normal trait (other than being in the prelude), and so requires being used like a normal trait, with method calls, etc. The Copy trait represents values that can … Read more

How do I convert a Vector of bytes (u8) to a string?

To convert a slice of bytes to a string slice (assuming a UTF-8 encoding): use std::str; // // pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> // // Assuming buf: &[u8] // fn main() { let buf = &[0x41u8, 0x41u8, 0x42u8]; let s = match str::from_utf8(buf) { Ok(v) => v, Err(e) => panic!(“Invalid UTF-8 sequence: {}”, … Read more

What is this question mark operator about?

As you may have noticed, Rust does not have exceptions. It has panics, but their use for error-handling is discouraged (they are meant for unrecoverable errors). In Rust, error handling uses Result. A typical example would be: fn halves_if_even(i: i32) -> Result<i32, Error> { if i % 2 == 0 { Ok(i / 2) } … Read more

How do I create a global, mutable singleton?

Non-answer answer Avoid global state in general. Instead, construct the object somewhere early (perhaps in main), then pass mutable references to that object into the places that need it. This will usually make your code easier to reason about and doesn’t require as much bending over backwards. Look hard at yourself in the mirror before … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)