How to initialize struct fields which reference each other

Not only is there an issue with initialization, there could also be issues with destruction, if GameIterator implemented Drop: the compiler would have to know that it needs to destruct game_iter before game_window, otherwise game_window would have a reference to a destroyed GameWindowGLFW while running its drop() method. There’s no way to pass the lifetime …

Read more

Is there any trait that specifies numeric functionality?

You can use num or num-traits crates and bound your generic function type with num::Float, num::Integer or whatever relevant trait: use num::Float; // 0.2.1 fn main() { let f1: f32 = 2.0; let f2: f64 = 3.0; let i1: i32 = 3; println!(“{:?}”, sqrt(f1)); println!(“{:?}”, sqrt(f2)); println!(“{:?}”, sqrt(i1)); // error } fn sqrt<T: Float>(input: T) …

Read more

How to make a compiled Regexp a global variable?

You can use the lazy_static macro like this: use lazy_static::lazy_static; // 1.3.0 use regex::Regex; // 1.1.5 lazy_static! { static ref RE: Regex = Regex::new(r”hello (\w+)!”).unwrap(); } fn main() { let text = “hello bob!\nhello sue!\nhello world!\n”; for cap in RE.captures_iter(text) { println!(“your name is: {}”, &cap[1]); } } If you are using the 2015 edition …

Read more

How to call a method when a trait and struct use the same method name?

To specify which method to call, whether inherent or provided from a trait, you want to use the fully qualified syntax: Type::function(maybe_self, needed_arguments, more_arguments) Trait::function(maybe_self, needed_arguments, more_arguments) Your case doesn’t work because Vec doesn’t have a method called get! get is provided from the Deref implementation to [T]. The easiest fix is to call as_slice …

Read more

Parameter type may not live long enough?

There are actually plenty of types that can “not live long enough”: all the ones that have a lifetime parameter. If I were to introduce this type: struct ShortLivedBee<‘a>; impl<‘a> Animal for ShortLivedBee<‘a> {} ShortLivedBee is not valid for any lifetime, but only the ones that are valid for ‘a as well. So in your …

Read more

How to convert iterator of chars to String?

.collect() is generic in what collection it produces, and it can produce the String for you! let s = “abc”.chars().collect::<String>(); The trait FromIterator determines which elements you can collect into which kind of collection, and among the implementors you can find String twice: impl FromIterator<char> for String impl<‘a> FromIterator<&’a str> for String Both iterators of …

Read more

How to swap two variables?

When swapping variables, the most likely thing you want is to create new bindings for a and b. fn main() { let (a, b) = (1, 2); let (b, a) = (a, a + b); } For your actual case, you want to modify the existing bindings. Rust 1.59 will stabilize destructuring assignment: fn fibonacci(n: …

Read more

How can I 0-pad a number by a variable amount when formatting with std::fmt?

You can use the :0_ format specifier with a variable: println!(“{:0width$}”, x, width = width); // prints 001234 Here it is running in the playground Likewise, if width <= 4, it just prints 1234. If width = 60, it prints: 000000000000000000000000000000000000000000000000000000001234 The format arguments also support ordinals, thus this also works: println!(“{:01$}”, x, width); The …

Read more

When should we use unwrap vs expect in Rust

Rust doesn’t have function overloading, so there should be a way to declare “unwrap with a message”, and that is expect. expect == unwrap with a message expect_err == unwrap_err with a message About usage scenarios of “unwrap vs expect” Rust Book (Ch 9) says: Using expect instead of unwrap and providing good error messages …

Read more

How do I serialize or deserialize an Arc in Serde?

Serde provides implementations of Serialize and Deserialize for Arc<T> and Rc<T>, but only if the rc feature is enabled. There’s a comment on Serde’s reference website explaining why: Opt into impls for Rc<T> and Arc<T>. Serializing and deserializing these types does not preserve identity and may result in multiple copies of the same data. Be …

Read more