Command-Line Rust
by Ken Youens-Clark
Copyright 2022 Charles Kenneth Youens-Clark. All rights reserved.
Printed in the United States of America.
Published by OReilly Media, Inc. , 1005 Gravenstein Highway North, Sebastopol, CA 95472.
OReilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com.
- Acquisitions Editor: Suzanne McQuade
- Development Editors: Rita Fernando and
Corbin Collins - Production Editors: Caitlin Ghegan and
Gregory Hyman - Copyeditor: Kim Sandoval
- Proofreader: Rachel Head
- Indexer: Ellen Troutman-Zaig
- Interior Designer: David Futato
- Cover Designer: Karen Montgomery
- Illustrator: Kate Dullea
- January 2022: First Edition
Revision History for the First Edition
- 2021-01-13: First Release
See http://oreilly.com/catalog/errata.csp?isbn=9781098109431 for release details.
The OReilly logo is a registered trademark of OReilly Media, Inc. Command-Line Rust, the cover image, and related trade dress are trademarks of OReilly Media, Inc.
The views expressed in this work are those of the author and do not represent the publishers views. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
978-1-098-10943-1
[LSI]
Preface
I already know the ending \ Its the part that makes your face implode
They Might Be Giants, Experimental Film (2004)
I remember back when this new language called JavaScript came out in 1995.A few years later, I decided to learn it, so I bought a big, thick reference book and read it cover to cover.The book was well written and thoroughly explained the language in great detail, from strings to lists and objects.But when I finished the book, I still couldnt write JavaScript to save my life.Without applying this knowledge by writing programs, I learned very little.Ive since improved at learning how to learn a language, which is perhaps the most valuable skill you can develop as a programmer.For me, that means rewriting programs I already know, like tic-tac-toe.
Rust is the new kid on the block now, and perhaps youve picked up this book to see what its all about.This book is not a reference on the language.Those already exist, and theyre quite good.Instead, Ive written a book that challenges you to write many small programs that probably will be familiar to you.Rust is reputed to have a fairly steep learning curve, but I believe this approach will help you quickly become productive with the language.
Specifically, youre going to write Rust versions of core Unix command-line tools such as head
and cal
.This will teach you more about the tools and why they are so wildly useful while also providing the context to use Rust concepts like strings, vectors, and filehandles.If you are not familiar with Unix or command-line programming, then you will learn about concepts like program exit values, command-line arguments, output redirection, pipes to connect one programs output (STDOUT
or standard out) to the input of another program (STDIN
or standard in), and how to use STDERR
(standard error) to segregate error messages from other output.The programs you write will reveal patterns that youll be able to use when you create your own Rust programspatterns like validating parameters, reading and writing files, parsing text, and using regular expressions.Many of these tools and concepts dont even exist on Windows, so users of that platform will create decent versions of several core Unix programs.
What Is Rust (and Why Is Everybody Talkin About It)?
Rust is a language empowering everyone to build reliable and efficient software.Rust was created by Graydon Hoare and many others around 2006, while Hoare was working at Mozilla Research.It gained enough interest and users that by 2010 Mozilla had sponsored the development effort.In the 2021 Stack Overflow Developer Survey, nearly 80,000 developers ranked Rust as the most loved language for the sixth year running.
Figure P-1. Here is a logo I made from an old Rush logo. As a kid playing the drums in the 1980s, I listened to a lot of Rush. Anyway, Rust is cool, and this logo proves it.
The language is syntactically similar to C, so youll find things like for
loops, semicolon-terminated statements, and curly braces denoting block structures.Crucially, Rust can guarantee memory safety through the use of a borrow checker that tracks which part of a program has safe access to different parts of memory.This safety does not come at the expense of performance, though.Rust programs compile to native binaries and often match or beat the speed of programs written in C or C++.For this reason, Rust is often described as a systems programming language that has been designed for performance and safety.
Rust is a statically typed language like C/C++ or Java.This means that a variable can never change its type, such as from a number to a string, for example.You dont always have to declare a variables type in Rust because the compiler can often figure it out from the context.This is in contrast to dynamically typed languages like Perl, JavaScript, or Python, where a variable can change its type at any point in the program, like from a string to a filehandle.
Rust is not an object-oriented (OO) language like C++ or Java, as there are no classes or inheritance in Rust.Instead, Rust uses a struct
(structure) to represent complex data types and traits to describe how types can behave.These structures can have methods, can mutate the internal state of the data, and might even be called objects in the documentation, but they are not objects in the formal sense of the word.
Rust has borrowed many exciting concepts from other languages and programming paradigms, including purely functional languages such as Haskell.For instance, variables in Rust are immutable by default, meaning they cant be changed from their initial value; you have to specifically inform the compiler that they are mutable.Functions are also first-class values, which means they can be passed as arguments to other so-called higher-order functions.Most exciting to my mind is Rusts use of enumerated and sum types, also called algebraic data types (ADTs), which allow you to represent, for instance, that a function can return a Result
that can be either an Ok
containing some value or an Err
containing some other kind of value.Any code that deals with these values must handle all possibilities, so youre never at risk of forgetting to handle an error that could unexpectedly crash your program.