How to print a Vec?

let v2 = vec![1; 10]; println!(“{:?}”, v2); {} is for strings and other values which can be displayed directly to the user. There’s no single way to show a vector to a user. The {:?} formatter can be used to debug it, and it will look like: [1, 1, 1, 1, 1, 1, 1, 1, … Read more

What does ‘let x = x’ do in Rust?

It makes fields immutable again. fields was previously defined as mutable (let mut fields = …;), to be used with sort_by_key which sorts in-place and requires the target to be mutable. The author has chosen here to explicitly prevent further mutability. “Downgrading” a mutable binding to immutable is quite common in Rust. Another common way … Read more

Unable to compile Rust hello world on Windows: linker link.exe not found

I downloaded and installed the Build Tools for Visual Studio 2019. During installation I selected the C++ tools. It downloaded almost 5GB of data. I restarted the machine after installation and compiling the code worked fine: > cargo run Compiling helloworld v0.1.0 (C:\Users\DELL\helloworld) Finished dev [unoptimized + debuginfo] target(s) in 12.05s Running `target\debug\helloworld.exe` Hello, world!

What is a “fat pointer”?

The term “fat pointer” is used to refer to references and raw pointers to dynamically sized types (DSTs) – slices or trait objects. A fat pointer contains a pointer plus some information that makes the DST “complete” (e.g. the length). Most commonly used types in Rust are not DSTs but have a fixed size known … Read more

Creating a vector of zeros for a specific size

To initialize a vector of zeros (or any other constant value) of a given length, you can use the vec! macro: let len = 10; let zero_vec = vec![0; len]; That said, your function worked for me after just a couple syntax fixes: fn zeros(size: u32) -> Vec<i32> { let mut zero_vec: Vec<i32> = Vec::with_capacity(size … Read more

What are non-lexical lifetimes?

It’s easiest to understand what non-lexical lifetimes are by understanding what lexical lifetimes are. In versions of Rust before non-lexical lifetimes are present, this code will fail: fn main() { let mut scores = vec![1, 2, 3]; let score = &scores[0]; scores.push(4); } The Rust compiler sees that scores is borrowed by the score variable, … Read more

Benchmarking programs in Rust

It might be worth noting two years later (to help any future Rust programmers who stumble on this page) that there are now tools to benchmark Rust code as a part of one’s test suite. (From the guide link below) Using the #[bench] attribute, one can use the standard Rust tooling to benchmark methods in … Read more