How to concatenate static strings in Rust

Since I was essentially trying to emulate C macros, I tried to solve the problem with Rust macros and succeeded: macro_rules! description { () => ( “my program” ) } macro_rules! version { () => ( env!(“CARGO_PKG_VERSION”) ) } macro_rules! version_string { () => ( concat!(description!(), ” v”, version!()) ) } It feels a bit … Read more

Can I convert a string to enum without macros in Rust?

You should implement std::str::FromStr trait. use std::str::FromStr; #[derive(Debug, PartialEq)] enum Foo { Bar, Baz, Bat, Quux, } impl FromStr for Foo { type Err = (); fn from_str(input: &str) -> Result<Foo, Self::Err> { match input { “Bar” => Ok(Foo::Bar), “Baz” => Ok(Foo::Baz), “Bat” => Ok(Foo::Bat), “Quux” => Ok(Foo::Quux), _ => Err(()), } } } fn … Read more

How to print structs and arrays?

You want to implement the Debug trait on your struct. Using #[derive(Debug)] is the easiest solution. Then you can print it with {:?}: #[derive(Debug)] struct MyStruct{ a: i32, b: i32 } fn main() { let x = MyStruct{ a: 10, b: 20 }; println!(“{:?}”, x); }

How to implement idiomatic operator overloading for values and references in Rust?

The great thing about Rust is that it’s open source. This means you can see how the authors of the language have solved a problem. The closest analogue is primitive integer types: macro_rules! add_impl { ($($t:ty)*) => ($( #[stable(feature = “rust1”, since = “1.0.0”)] impl Add for $t { type Output = $t; #[inline] fn … Read more

What is the null pointer optimization in Rust?

The null pointer optimization basically means that if you have an enum with two variants, where one variant has no associated data, and the other variant has associated data where the bit pattern of all zeros isn’t a valid value, then the enum itself will take exactly the same amount of space as that associated … Read more

Is there a good way to convert a Vec to an array?

Arrays must be completely initialized, so you quickly run into concerns about what to do when you convert a vector with too many or too few elements into an array. These examples simply panic. As of Rust 1.51 you can parameterize over an array’s length. use std::convert::TryInto; fn demo<T, const N: usize>(v: Vec<T>) -> [T; … Read more