Book Image

The Complete Rust Programming Reference Guide

By : Rahul Sharma, Vesa Kaihlavirta, Claus Matzinger
Book Image

The Complete Rust Programming Reference Guide

By: Rahul Sharma, Vesa Kaihlavirta, Claus Matzinger

Overview of this book

Rust is a powerful language with a rare combination of safety, speed, and zero-cost abstractions. This Learning Path is filled with clear and simple explanations of its features along with real-world examples, demonstrating how you can build robust, scalable, and reliable programs. You’ll get started with an introduction to Rust data structures, algorithms, and essential language constructs. Next, you will understand how to store data using linked lists, arrays, stacks, and queues. You’ll also learn to implement sorting and searching algorithms, such as Brute Force algorithms, Greedy algorithms, Dynamic Programming, and Backtracking. As you progress, you’ll pick up on using Rust for systems programming, network programming, and the web. You’ll then move on to discover a variety of techniques, right from writing memory-safe code, to building idiomatic Rust libraries, and even advanced macros. By the end of this Learning Path, you’ll be able to implement Rust for enterprise projects, writing better tests and documentation, designing for performance, and creating idiomatic Rust code. This Learning Path includes content from the following Packt products: • Mastering Rust - Second Edition by Rahul Sharma and Vesa Kaihlavirta • Hands-On Data Structures and Algorithms with Rust by Claus Matzinger
Table of Contents (29 chapters)
Title Page
Copyright
About Packt
Contributors
Preface
Index

Consts in structs, enums, and traits


Structs, enums, and traits definitions can also be provided with constant field members. They can be used in cases where you need to share a constant among them. Take, for example, a scenario where we have a Circle trait that's is meant to be implemented by different circular shape types. We can add a PI constant to the Circle trait, which can be shared by any type that has an  area property and relies on value of PI for calculating the area:

// trait_constants.rs

trait Circular {
    const PI: f64 = 3.14;
    fn area(&self) -> f64;
}

struct Circle {
    rad: f64
}

impl Circular for Circle {
    fn area(&self) -> f64 {
        Circle::PI * self.rad * self.rad
    }
}

fn main() {
    let c_one = Circle { rad: 4.2 };
    let c_two = Circle { rad: 75.2 };
    println!("Area of circle one: {}", c_one.area());
    println!("Area of circle two: {}", c_two.area());
}

We can also have consts in structs and enums:

// enum_struct_consts.rs

enum...