Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Rust

You're reading from   Mastering Rust Learn about memory safety, type system, concurrency, and the new features of Rust 2018 edition

Arrow left icon
Product type Paperback
Published in Jan 2019
Publisher Packt
ISBN-13 9781789346572
Length 554 pages
Edition 2nd Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
Vesa Kaihlavirta Vesa Kaihlavirta
Author Profile Icon Vesa Kaihlavirta
Vesa Kaihlavirta
Rahul Sharma Rahul Sharma
Author Profile Icon Rahul Sharma
Rahul Sharma
Arrow right icon
View More author details
Toc

Table of Contents (19) Chapters Close

Preface 1. Getting Started with Rust FREE CHAPTER 2. Managing Projects with Cargo 3. Tests, Documentation, and Benchmarks 4. Types, Generics, and Traits 5. Memory Management and Safety 6. Error Handling 7. Advanced Concepts 8. Concurrency 9. Metaprogramming with Macros 10. Unsafe Rust and Foreign Function Interfaces 11. Logging 12. Network Programming in Rust 13. Building Web Applications with Rust 14. Interacting with Databases in Rust 15. Rust on the Web with WebAssembly 16. Building Desktop Applications with Rust 17. Debugging 18. Other Books You May Enjoy

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...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime