This practical book introduces systems programmers to Rust, the new and cutting-edge language that’s still in the experimental/lab stage. You’ll learn how Rust offers the rare and valuable combination of statically verified memory safety and low-level control—imagine C++, but without dangling pointeProgramming RustAuthor nameBeijing: Boston. Farnham. Sebastopol. Tokyo OREILLYProgramming Rustby Jim Blandy and Jason OrendorffCopyright O 2016 Jim Blandy & Jason Orendorff. All rights reservedPrinted in the United States of AmericaPublished by o reilly Media, InC, 1005 Gravenstein Highway North, Sebastopol, CA 95472OReilly books may be purchased for educational, business, or sales promotional use Online editions arealsoavailableformosttitles(http://safaribooksonline.com).Formoreinformationcontactourcorporaterinstitutionalsalesdepartment800-998-9938orcorporate@oreilly.comEditors: Brian Mac Donald and Meghan Blanchette Proofreader FILL IN PROOFREADERProduction Editor: FILL IN PRODUCTION EDI- Indexer: FILL IN INDEXERTORInterior Designer: David FutatoCopyeditor: FILL IN COPYEDITORCover Designer: Karen montgomeryustrator: Rebecca demarestMarch 2016:First editionRevision history for the first Edition2016-03-07: First Early ReleaseSeehttp://oreilly.com/catalog/errata.csp?isbn=9781491927212forreleasedetailsThe O Reilly logo is a registered trademark of O Reilly Media, Inc. Programming Rust, the cover image,and related trade dress are trademarks of o reilly media, IncWhile the publisher and the author(s)have used good faith efforts to ensure that the information andinstructions contained in this work are accurate, the publisher and the author(s) disclaim all responsibil-ity for errors or omissions, including without limitation responsibility for damages resulting from the useof or reliance on this work. Use of the information and instructions contained in this work is at your ownrisk. If any code samples or other technology this work contains or describes is subject to open sourcelicenses or the intellectual property rights of others, it is your responsibility to ensure that your usethereof complies with such licenses and/or rights978-1-491-92721-2IFILL INITable of contents1. Why rust?............Type Safet2. A Tour of rust, .......4...........................13Downloading and installing rust13A simple function16Writing and running unit tests17Handling command-line arguments18A simple web server21Concurrency28Parsing pair command-line arguments29Mapping from pixels to complex numbers31Mandelbrot membership calculation32Writing bitmap files34A concurrent Mandelbrot program35Running the mandelbrot plotter38Safety is invisible403. Basic types41Machine types44Integer typesFloating-point types47The bool type48CharactersTuplP50Pointer types52References53BoxesRaw pointers53Arrays, Vectors, and Slices53arrays54VectorsSlices58String typesString literals60Byte strings61Strings in memory61String62Using strings63Other string-like typesBeyond the basics4. Ownership and movesOwnership66Moves71More operations that moveMoves and control flow78Copy types: the exception to moves81Rc and Arc: shared ownership835. References and borrowing.. ...............................................87References as valuesImplicit dereferencingassigning references92References to slices and trait objects93References are never null93Borrowing references to arbitrary expressions94Reference safety94Bborrowing a local variable94Receiving references as parametersPassing references as arguments100Returning references101Structures containing references102Distinct lifetime parameters104Sharing versus mutation105Reference counting: Rc and arc1136. Expressions...,,115An expression language115Blocks and statements116iv Table of ContentsDeclarations117if and match119LOops121return expressions123y Rust has Loop124Names, paths, and use125ClosuresFunction and method calls126Fields and elements127Reference operators128Arithmetic, bitwise, comparison, and logical operators129assignment130Type casts130Precedence and associativityOnward1337. Enums and patterns.................135Enums135Tuple and struct variants137Enums in memory138Rich data structures using enums139Generic enums141Patterns143Tuple and struct patterns144Reference patterns146Matching multiple possibilities147Pattern guards148patterns148Where patterns are allowed149Populating a binary tree150The big picture151Table of contentsCHAPTER 1Why rust?Systems programming languages have come a long way in the 50 years since westarted using high-level languages to write operating systems, but two thorny problems in particular have proven difficult to crackIt's difficult to write secure code. It's common for security exploits to leveragebugs in the way C and C++ programs handle memory, and it has been so at leastsince the morris virus, the first internet virus to be carefully analyzed, tookadvantage of a buffer overflow bug to propagate itself from one machine to thenext in 1988It's very difficult to write multithreaded code, which is the only way to exploit theabilities of modern machines. Each new generation of hardware brings us,instead of faster processors, more of them; now even midrange mobile deviceshave multiple cores. Taking advantage of this entails writing multithreaded codebut even experienced programmers approach that task with caution: concurrencyintroduces broad new classes of bugs, and can make ordinary bugs much harderto reproduceThese are the problems Rust was made to addressRust is a new systems programming language designed by Mozilla. Like C and C++Rust gives the developer fine control over the use of memory, and maintains a closerelationship between the primitive operations of the language and those of themachines it runs on, helping developers anticipate their codes costs. Rust shares theambitions Bjarne Stroustrup articulates for C++ in his paper Abstraction and the C+machine modelIn general, C++ implementations obey the zero-overhead principle: What you dontuse,you don't pay for. And further: What you do use, you couldnt hand code any betterTo these rust adds its own goals of memory safety and data-race-free concurrency.The key to meeting all these promises is Rusts novel system of ownership, moves, andborrows,checked at compile time and carefully designed to complement rust's flexi-ble static type system. The ownership system establishes a clear lifetime for eachvalue, making garbage collection unnecessary in the core language, and enablingsound but flexible interfaces for managing other sorts of resources like sockets andfile handlesThese same ownership rules also form the foundation of Rusts trustworthy concurrency model. Most languages leave the relationship between a mutex and the data it'smeant to protect to the comments; Rust can actually check at compile time that yourcode locks the mutex while it accesses the data. Most languages admonish you to besure not to use a data structure yourself after you' ve sent it via a channel to anotherthread; Rust checks that you dont. Rust is able to prevent data races at compile timeMozilla and samsung have been collaborating on an experimental new web browserengine named Servo, written in Rust. Servo's needs and Rusts goals are well matchedsS programs whose primary use is handling untrusted data, browsers must be secureand as the Web is the primary interactive medium of the modern Net, browsers mustperform well. Servo takes advantage of Rust's sound concurrency support to exploitas much parallelism as its developers can find, without compromising its stability. Asof this writing, Servo is roughly 100,000 lines of code, and rust has adapted over timeto meet the demands of development at this scaleType SafetyBut what do we mean by "type safety"? Safety sounds good, but what exactly are webeing kept safe fromHere's the definition of undefined behavior" from the 1999 standard for the c pro-gramming language, known as"C99"3.4.3undefined behaviorbehavior, upon use of a nonportable or erroneous program construct or of erroneousdata, for which this International Standard imposes no requirementsConsider the following C programint main(int argc, char **argv)iunsigned long a[1];3= 0x7ffff7b36cebULreturn o8Chapter 1: Why Rust?