Book Image

Learning Rust

By : Vesa Kaihlavirta
Book Image

Learning Rust

By: Vesa Kaihlavirta

Overview of this book

Rust is a highly concurrent and high performance language that focuses on safety and speed, memory management, and writing clean code. It also guarantees thread safety, and its aim is to improve the performance of existing applications. Its potential is shown by the fact that it has been backed by Mozilla to solve the critical problem of concurrency. Learning Rust will teach you to build concurrent, fast, and robust applications. From learning the basic syntax to writing complex functions, this book will is your one stop guide to get up to speed with the fundamentals of Rust programming. We will cover the essentials of the language, including variables, procedures, output, compiling, installing, and memory handling. You will learn how to write object-oriented code, work with generics, conduct pattern matching, and build macros. You will get to know how to communicate with users and other services, as well as getting to grips with generics, scoping, and more advanced conditions. You will also discover how to extend the compilation unit in Rust. By the end of this book, you will be able to create a complex application in Rust to move forward with.
Table of Contents (21 chapters)
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Customer Feedback
Title Page
Preface
Free Chapter
1
Introducing and Installing Rust
4
Conditions, Recursion, and Loops

Trait objects


Typically, when we call a function in Rust, we will have a line in the code similar to this:

call_some_method(some_value);

When we have a struct in the code which has an impl attached to it, we will have this:

let m = MyStruct {a: 3, b: 4, c: 1, d: 4}; m.call_some_method();

These are both fine.

If you recall, back in the generic_trait_full example, we had Calc defined and T could be either an f32 or i32. We also talked about how the application knew what to include in the final binary. This is known as static dispatch (which Rust prefers).

Rust uses a system called a dispatch, of which there are two types: static (favored by Rust) and dynamic. Dynamic dispatch relies on something called a trait object.

Let's create a sample test setup

The test code is very simple. We have a trait with a function that returns a String. We then have a couple of implementations and a parameter bound function that will display the result from the implementations:

trait StaticObject 
{ 
  fn static_method...