Is there a faster/shorter way to initialize variables in a Rust struct?

You can provide default values for your struct by implementing the Default trait. The default function would look like your current new function: impl Default for cParams { fn default() -> cParams { cParams { iInsertMax: -1, iUpdateMax: -1, iDeleteMax: -1, iInstanceMax: -1, tFirstInstance: false, tCreateTables: false, tContinue: false, } } } You can then … Read more

Cannot move out of borrowed content / cannot move out of behind a shared reference

Let’s look at the signature for into_bytes: fn into_bytes(self) -> Vec<u8> This takes self, not a reference to self (&self). That means that self will be consumed and won’t be available after the call. In its place, you get a Vec<u8>. The prefix into_ is a common way of denoting methods like this. I don’t … Read more

Idiomatic callbacks in Rust

Short answer: For maximum flexibility, you can store the callback as a boxed FnMut object, with the callback setter generic on callback type. The code for this is shown in the last example in the answer. For a more detailed explanation, read on. “Function pointers”: callbacks as fn The closest equivalent of the C++ code … Read more

What’s the difference between use and extern?

extern crate foo indicates that you want to link against an external library and brings the top-level crate name into scope (equivalent to use foo). As of Rust 2018, in most cases you won’t need to use extern crate anymore because Cargo informs the compiler about what crates are present. (There are one or two … Read more

How do I stop iteration and return an error when Iterator::map returns a Result::Err?

Result implements FromIterator, so you can move the Result outside and iterators will take care of the rest (including stopping iteration if an error is found). #[derive(Debug)] struct Item; type Id = String; fn find(id: &Id) -> Result<Item, String> { Err(format!(“Not found: {:?}”, id)) } fn main() { let s = |s: &str| s.to_string(); let … Read more

How to convert a String into a &’static str

Updated for Rust 1.0 You cannot obtain &’static str from a String because Strings may not live for the entire life of your program, and that’s what &’static lifetime means. You can only get a slice parameterized by String own lifetime from it. To go from a String to a slice &’a str you can … Read more

How to lookup from and insert into a HashMap efficiently?

The entry API is designed for this. In manual form, it might look like let values = match map.entry(key) { Entry::Occupied(o) => o.into_mut(), Entry::Vacant(v) => v.insert(default), }; One can use the briefer form via Entry::or_insert_with: let values = map.entry(key).or_insert_with(|| default); If default is already computed, or if it’s OK/cheap to compute even when it isn’t … Read more