28,14 €
Get familiar with writing programs in the trending new systems programming language that brings together the powerful performance of low-level languages with the advanced features like thread safety in multi-threaded code
Key Features
Book Description
Rust is an emerging programming language applicable to areas such as embedded programming, network programming, system programming, and web development. This book will take you from the basics of Rust to a point where your code compiles and does what you intend it to do!
This book starts with an introduction to Rust and how to get set for programming, including the rustup and cargo tools for managing a Rust installation and development workflow.
Then you'll learn about the fundamentals of structuring a Rust program, such as functions, mutability, data structures, implementing behavior for types, and many more. You will also learn about concepts that Rust handles differently from most other languages.
After understanding the Basics of Rust programming, you will learn about the core ideas, such as variable ownership, scope, lifetime, and borrowing. After these key ideas, you will explore making decisions in Rust based on data types by learning about match and if let expressions. After that, you'll work with different data types in Rust, and learn about memory management and smart pointers.
What you will learn
Who this book is for
This book is for people who are new to Rust, either as their first programming language or coming to it from somewhere else. Familiarity with computer programming in any other language will be helpful in getting the best out of this book.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 226
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author(s), nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Aditi GourAcquisition Editor: Siddharth MandalContent Development Editor: Smit CarvalhoTechnical Editor: Sushmeeta JenaCopy Editor: Safis EditingProject Coordinator: Hardik BhindeProofreader: Safis EditingIndexer:Pratik ShirodkarGraphics:Alishon MendonsaProduction Coordinator: Shantanu Zagade
First published: October 2018
Production reference: 1291018
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78961-670-5
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Daniel Arbuckle is a long-time professional programmer and teacher of programming, and the author of several books on the topic as well. He first started programming on GBASIC on a North Star Advantage running CP/M, but as the PC revolution expanded, his repertoire expanded as well. Daniel loves programming languages, and by the time he'd gotten his PhD in computer science he knew most of the extant languages well.
Rust is one of his favorite of the current crop of programming languages.
Daniel Durante is an avid motorcyclist, archer, welder, and carpenter whenever he isn't programming. From the age of 12 years old he has been involved with web, system, and embedded programming with PHP, Node.js, Golang, Rust, C++, and C.
He has worked on text-based browser games that have reached over 1 million active players, created bin-packing software for CNC machines, embedded programming with cortex-m and PIC circuits, worked on high-frequency trading applications, and helped contribute to one of the oldest ORMs of Node.js (SequelizeJS).
Syed Omar Faruk Towaha has degrees in physics and computer engineering. He is a technologist, a tech speaker, and a physics lover from Shahjalal University of Science and Technology, Sylhet. He has a passion for programming, tech writing, and physics experiments.
His recent work includes Easy Circuits for Kids, Fundamentals of Ruby, and How You Should Design Algorithms. He is an Oracle Certified Professional Developer and is currently involved with a number of projects that serve both physics and computer architecture.
He is the president of one of the largest astronomical organizations (CAM-SUST) in Bangladesh. He volunteers for Mozilla as a representative.
Walt Stoneburner is a software architect, systems designer, and full-stack developer with over 30 years of enterprise-grade commercial application development and consulting experience. He is currently concentrating on concurrency, cloud services, Docker containers, microservice technologies, and web frameworks. He has a background working with search engine technologies, knowledge management, authoring DSLs, designing APIs, and enjoys creating automation processes.
Fringe passions include typography, illustration and layout, user interface design, psychology and social engineering, quality assurance, configuration management, and security. If cornered, he may admit to liking statistics and authoring documentation as well.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Rust Quick Start Guide
Packt Upsell
Why subscribe?
Packt.com
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Getting Ready
Installing Rust
Starting a new project
Project metadata
Dependencies on libraries from crates.io
Dependencies on Git repositories
Dependencies on local libraries
Automatically generated source files
Compiling our project
Debug and release builds
Dynamic libraries, software distribution, and Rust
Using crates.io
Summary
Basics of the Rust Language
Functions
Defining a function
Modules
Defining a module
A module as a section of a file
A module as a separate file
Accessing module contents from outside
Using the item's full name directly
Using the item's short name
Public and private module items
Expressions
Literal expressions
Operator expressions
Array and tuple expressions
Block expressions
Branch expressions
Loop expressions
while loops
for loops
Variables, types, and mutability
Type inference
Data structures
Mutability of data structures
More about functions
Parameters
Return types
Error handling
Using Result to signal success or failure
Calling functions that return Result
Implementing behavior for types
Summary
The Big Ideas – Ownership and Borrowing
Scope and ownership
The stack
Transferring ownership
Copying
Lending
Lending immutably
Lending mutably
Accessing borrowed data
The lifetime of borrowed data
Ownership and the self parameter
Moving self
Borrowing self
Mutably borrowing self
Summary
Making Decisions by Pattern Matching
Variable assignment with pattern matching
Using if let expressions to test whether a pattern matches
Using match to choose one of several patterns
Using don't care in patterns
Moving and borrowing in pattern matches
Matching tuples and other more complex patterns
Nested patterns
Storing a matched value and comparing it to a pattern
Ignoring most of a data structure
Gotchas
Not all values can be matched against a literal pattern
Patterns assign values to variable names
Summary
One Data Type Representing Multiple Kinds of Data
Enumerations
Basic enumerations
Parameterized enumerations
Checking the value type and extracting parameter values
Result is an enumeration, accessed via the prelude
Traits and trait objects
Traits
Implementing our PrintableDirection trait
Trait objects
Using our PrintableDirection trait
Trait objects only provide access to the trait interface
Any
Any can store almost anything
But to access it we have to already know about the real data type
Comparison of these techniques
Summary
Heap Memory and Smart Pointers
Box
Box and variable size
Box and Any
Vec and String
String
Vec
Rc
Weak references
Cell and RefCell
Cell
What's the point?
RefCell
Arc
Mutex and RwLock
Summary
Generic Types
Types with generic type parameters
Limiting what types can be used for type parameters
Implementing functionality for types with generic type parameters
Using generic types as function return values
Compiler errors involving generic type parameters
Generic types on functions outside of implementation blocks
Alternative ways to write trait bounds
Generic types versus trait objects
Higher-order functions and trait bounds that represent functions
Complete implementation of a binary tree with generic type parameters
Summary
Important Standard Traits
Traits that can be derived
Clone
Copy
Debug
PartialEq
Eq
PartialOrd
Ord
Hash
Default
Traits that enable operators
​Add, Mul, Sub, and Div
AddAssign, MulAssign, SubAssign, and DivAssign
BitAnd
BitAndAssign
BitOr
BitOrAssign
BitXor
BitXorAssign
Deref
DerefMut
Drop
Index
IndexMut
Neg
Not
Rem and RemAssign
Shl and ShlAssign
Shr and ShrAssign
Traits that are implemented automatically
Sync
Send
Sized
Fn
FnMut
FnOnce
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Rust is system-level programming language with growing popularity. This popularity is driven by its semantics, which encourages the creation of fast, reliable software. In this book, we're going to learn the basics of the language, eventually getting to a point where we can begin writing usable programs.
This book is for people with an interest in learning the increasingly popular Rust programming language. You do not have to be a programmer already, but it will help if you are.
Chapter 1, Getting Ready, teaches how to install Rust and use the supporting tools cargo and rustup.
Chapter 2, Basics of the Rust Language, teaches the basic language syntax and fundamental semantic constructs.
Chapter 3, The Big Ideas – Ownership and Borrowing, discusses the things that set Rust apart from other programming languages.
Chapter 4, Making Decisions by Pattern Matching, explains how to use if let and match expressions.
Chapter 5, One Date Type Representing Multiple Kinds of Data, covers enumerations and trait objects.
Chapter 6, Heap Memory and Smart Pointers, explores the Box, Rc, RefCell, Arc, Mutex, and RwLock smart pointers.
Chapter 7, Generic Types, explains how to use generic type parameters with our data types.
Chapter 8, Important Standard Traits, covers traits that integrate with the language syntax and affect the behavior of the compiler.
At least some familiarity with another programming language will be helpful, for comparison and contrast. You will need an internet connection to download and install the compiler toolchain. The ability to use command-line tools is assumed.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Rust-Quick-Start-Guide. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781789616705_ColorImages.pdf.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
In this guide, we're going to learn the basics of working with Rust, a systems-level programming language that has been making a name for itself over the last few years. Rust is a strict language, designed to make the most common errors impossible and less common errors obvious.
Being a systems-level language means that Rust is guided by the needs of low-level programs that don't have a safety net, because they are the safety net for higher-level programs. Operating system kernels, web browsers, and other critical pieces of infrastructure are systems-level applications.
This is not to say that Rust can only be used for writing critical infrastructure, of course. The efficiency and reliability of Rust code can benefit any program. It's just that the priorities for higher-level code can be different.
In this chapter, we're going to cover the following topics:
The
rustup
tool
The
cargo
tool
How to start a new Rust project
How to compile a Rust project
How to locate third-party libraries
How to manage dependencies
How to keep a Rust installation up-to-date
How to switch between stable and beta Rust
Installing Rust on any supported platform is simple. All we need to do is navigate to https://rustup.rs/. That page will give us a single-step procedure to install the command-line Rust compiler. The procedure differs slightly depending on the platform, but it's never difficult. Here we see the rustup.rs page for Linux:
The installer doesn't just install the Rust compiler, it also installs a tool called rustup that can be used at any time to upgrade our compiler to the latest version. To do this, all we have to do is open up a command-line (or Terminal) window, and type: rustup update.
Upgrading the compiler needs to be simple because the Rust project uses a six-week rapid release schedule, meaning there's a new version of the compiler every six weeks, like clockwork. Each release contains whatever new features have been deemed to be stable in the six weeks since the previous release, in addition to the features of previous releases.
If we aren't willing to wait for a feature to be vetted and stabilized, for whatever reason, we can also use rustup to download, install, and update the beta or nightly releases of the compiler.
To download and install the beta compiler, we just need to type this: rustup toolchain install beta.
From that point on, when we use rustup to update our compiler, it will make sure that we have the newest versions of both the stable and beta compilers. We can then make the beta compiler active with rustup default beta.
Please note that the beta compiler is not the same thing as the next release of the stable compiler. The beta version is where features live before they graduate to stable, and features can and do remain in beta for years.
The nightly version is at most 24 hours behind the development code repository, which means that it might be broken in any number of ways. It's not particularly useful unless you're actually participating in the development of Rust itself. However, should you want to try it out, rustup can install and update it as well. You might also find yourself depending on a library that someone else has written that depends on features that only exist in the nightly build, in which case you'll need to tell rustup that you need the nightly build, too.
One of the things rustup will install is a tool called cargo, which we'll be seeing a lot of in this chapter, and using behind the scenes for the rest of this book. The cargo tool is the frontend to the whole Rust compiler system: it is used for creating new Rust project directories containing the initial boilerplate code for a program or library, for installing and managing dependencies, and for compiling Rust programs, among other things.
Okay, so we've installed the compiler. Yay! But how do we use it?
The first step is to open up a command-line window, and navigate to the directory where we want to store our new project. Then we can create the skeleton of a new program with cargo new foo.
When we do this, cargo will create a new directory named foo and set up the skeletal program inside it.
The default is for cargo to create the skeleton of an executable program, but we can also tell it to set up a new library for us. All that takes is an additional command-line argument (bar is the name of the new directory that will be created, like foo): cargo new --lib bar.
When we look inside the newly created foo directory, we see a file called Cargo.toml and a sub-directory called src. There may also be a Git version control repository, which we will ignore for now.
The Cargo.toml file is where metadata about the program is stored. That includes the program's name, version number, and authors, but importantly it also has a section for dependencies. Editing the content of the [dependencies] section is how we tell Rust that our code should be linked to external libraries when it is compiled, which libraries and versions to use, and where to find them. External libraries are collections of source code that were packaged up in order to make them easy to use as components of other programs. By finding and linking good libraries, we can save the time and effort of writing our whole program ourselves. Instead, we can write only the part that nobody else has already done.
The basic command to compile a Rust program is simple: cargo build.
We need to be in the directory containing Cargo.toml (or any subdirectory of that directory) in order to be able to do this, since that's how the cargo program knows which project to compile. However, we don't need to give it any other information, since everything it needs to know is in the metadata file.
Here, we see the result of building the chapter02 source code:
The warnings are expected and do not prevent the compile from succeeding. If we look at those warnings carefully, we can see that Rust is a lot more helpful with its warnings than many programming languages, giving us hints for improving efficiency and such, rather than just talking about language syntax.
When we build the program, a Cargo.lock file and target directory are created.
Cargo.lock
