SlideShare a Scribd company logo
The Rust Programming Language Second Edition 2
Converted Steve Klabnik download
https://ebookbell.com/product/the-rust-programming-language-
second-edition-2-converted-steve-klabnik-48000090
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
The Rust Programming Language 2nd Edition Second Converted Steve
Klabnik Carol Nichols
https://ebookbell.com/product/the-rust-programming-language-2nd-
edition-second-converted-steve-klabnik-carol-nichols-49465120
The Rust Programming Language Covers Rust 2018 Illustrated Steve
Klabnik
https://ebookbell.com/product/the-rust-programming-language-covers-
rust-2018-illustrated-steve-klabnik-50194554
The Rust Programming Language Steve Klabnik Carol Nichols
https://ebookbell.com/product/the-rust-programming-language-steve-
klabnik-carol-nichols-36194546
The Rust Programming Language Covers Rust 2018 Steve Klabnik Carol
Nichols
https://ebookbell.com/product/the-rust-programming-language-covers-
rust-2018-steve-klabnik-carol-nichols-49850560
The Rust Programming Language 1st Edition The Rust Project Developpers
https://ebookbell.com/product/the-rust-programming-language-1st-
edition-the-rust-project-developpers-23358024
The Rust Programming Language Steve Klabnik Carol Nichols
https://ebookbell.com/product/the-rust-programming-language-steve-
klabnik-carol-nichols-27553790
The Rust Programming Language Steve Klabnik Steve Carol Nichols
https://ebookbell.com/product/the-rust-programming-language-steve-
klabnik-steve-carol-nichols-36194548
The Rust Programming Language Covers Rust 2018 Carol Nichols
https://ebookbell.com/product/the-rust-programming-language-covers-
rust-2018-carol-nichols-37721398
The Rust Programming Language Steve Klabnik Carol Nichols
https://ebookbell.com/product/the-rust-programming-language-steve-
klabnik-carol-nichols-42174614
The Rust Programming Language Second Edition 2 Converted Steve Klabnik
The Rust Programming Language Second Edition 2 Converted Steve Klabnik
CONTENTS IN DETAIL
TITLE PAGE
COPYRIGHT
ABOUT THE AUTHORS
FOREWORD
PREFACE
ACKNOWLEDGMENTS
INTRODUCTION
Who Rust Is For
Teams of Developers
Students
Companies
Open Source Developers
People Who Value Speed and Stability
Who This Book Is For
How to Use This Book
Resources and How to Contribute to This Book
CHAPTER 1: GETTING STARTED
Installation
Installing rustup on Linux or macOS
Installing rustup on Windows
Troubleshooting
Updating and Uninstalling
Local Documentation
Hello, World!
Creating a Project Directory
Writing and Running a Rust Program
Anatomy of a Rust Program
Compiling and Running Are Separate Steps
Hello, Cargo!
Creating a Project with Cargo
Building and Running a Cargo Project
Building for Release
Cargo as Convention
Summary
CHAPTER 2: PROGRAMMING A GUESSING GAME
Setting Up a New Project
Processing a Guess
Storing Values with Variables
Receiving User Input
Handling Potential Failure with Result
Printing Values with println! Placeholders
Testing the First Part
Generating a Secret Number
Using a Crate to Get More Functionality
Generating a Random Number
Comparing the Guess to the Secret Number
Allowing Multiple Guesses with Looping
Quitting After a Correct Guess
Handling Invalid Input
Summary
CHAPTER 3: COMMON PROGRAMMING CONCEPTS
Variables and Mutability
Constants
Shadowing
Data Types
Scalar Types
Compound Types
Functions
Parameters
Statements and Expressions
Functions with Return Values
Comments
Control Flow
if Expressions
Repetition with Loops
Summary
CHAPTER 4: UNDERSTANDING OWNERSHIP
What Is Ownership?
Ownership Rules
Variable Scope
The String Type
Memory and Allocation
Ownership and Functions
Return Values and Scope
References and Borrowing
Mutable References
Dangling References
The Rules of References
The Slice Type
String Slices
Other Slices
Summary
CHAPTER 5: USING STRUCTS TO STRUCTURE RELATED DATA
Defining and Instantiating Structs
Using the Field Init Shorthand
Creating Instances from Other Instances with Struct
Update Syntax
Using Tuple Structs Without Named Fields to Create D
ifferent Types
Unit-Like Structs Without Any Fields
An Example Program Using Structs
Refactoring with Tuples
Refactoring with Structs: Adding More Meaning
Adding Useful Functionality with Derived Traits
Method Syntax
Defining Methods
Methods with More Parameters
Associated Functions
Multiple impl Blocks
Summary
CHAPTER 6: ENUMS AND PATTERN MATCHING
Defining an Enum
Enum Values
The Option Enum and Its Advantages Over Null Values
The match Control Flow Construct
Patterns That Bind to Values
Matching with Option<T>
Matches Are Exhaustive
Catch-All Patterns and the _ Placeholder
Concise Control Flow with if let
Summary
CHAPTER 7: MANAGING GROWING PROJECTS WITH PACKAGES, CRAT
ES, AND MODULES
Packages and Crates
Defining Modules to Control Scope and Privacy
Paths for Referring to an Item in the Module Tree
Exposing Paths with the pub Keyword
Starting Relative Paths with super
Making Structs and Enums Public
Bringing Paths into Scope with the use Keyword
Creating Idiomatic use Paths
Providing New Names with the as Keyword
Re-exporting Names with pub use
Using External Packages
Using Nested Paths to Clean Up Large use Lists
The Glob Operator
Separating Modules into Different Files
Summary
CHAPTER 8: COMMON COLLECTIONS
Storing Lists of Values with Vectors
Creating a New Vector
Updating a Vector
Reading Elements of Vectors
Iterating Over the Values in a Vector
Using an Enum to Store Multiple Types
Dropping a Vector Drops Its Elements
Storing UTF-8 Encoded Text with Strings
What Is a String?
Creating a New String
Updating a String
Indexing into Strings
Slicing Strings
Methods for Iterating Over Strings
Strings Are Not So Simple
Storing Keys with Associated Values in Hash Maps
Creating a New Hash Map
Accessing Values in a Hash Map
Hash Maps and Ownership
Updating a Hash Map
Hashing Functions
Summary
CHAPTER 9: ERROR HANDLING
Unrecoverable Errors with panic!
Recoverable Errors with Result
Matching on Different Errors
Propagating Errors
To panic! or Not to panic!
Examples, Prototype Code, and Tests
Cases in Which You Have More Information Than the Co
mpiler
Guidelines for Error Handling
Creating Custom Types for Validation
Summary
CHAPTER 10: GENERIC TYPES, TRAITS, AND LIFETIMES
Removing Duplication by Extracting a Function
Generic Data Types
In Function Definitions
In Struct Definitions
In Enum Definitions
In Method Definitions
Performance of Code Using Generics
Traits: Defining Shared Behavior
Defining a Trait
Implementing a Trait on a Type
Default Implementations
Traits as Parameters
Returning Types That Implement Traits
Using Trait Bounds to Conditionally Implement Method
s
Validating References with Lifetimes
Preventing Dangling References with Lifetimes
The Borrow Checker
Generic Lifetimes in Functions
Lifetime Annotation Syntax
Lifetime Annotations in Function Signatures
Thinking in Terms of Lifetimes
Lifetime Annotations in Struct Definitions
Lifetime Elision
Lifetime Annotations in Method Definitions
The Static Lifetime
Generic Type Parameters, Trait Bounds, and Lifetimes To
gether
Summary
CHAPTER 11: WRITING AUTOMATED TESTS
How to Write Tests
The Anatomy of a Test Function
Checking Results with the assert! Macro
Testing Equality with the assert_eq! and assert_ne!
Macros
Adding Custom Failure Messages
Checking for Panics with should_panic
Using Result<T, E> in Tests
Controlling How Tests Are Run
Running Tests in Parallel or Consecutively
Showing Function Output
Running a Subset of Tests by Name
Ignoring Some Tests Unless Specifically Requested
Test Organization
Unit Tests
Integration Tests
Summary
CHAPTER 12: AN I/O PROJECT: BUILDING A COMMAND LINE PROG
RAM
Accepting Command Line Arguments
Reading the Argument Values
Saving the Argument Values in Variables
Reading a File
Refactoring to Improve Modularity and Error Handling
Separation of Concerns for Binary Projects
Fixing the Error Handling
Extracting Logic from main
Splitting Code into a Library Crate
Developing the Library’s Functionality with Test-Drive
n Development
Writing a Failing Test
Writing Code to Pass the Test
Working with Environment Variables
Writing a Failing Test for the Case-Insensitive Sear
ch Function
Implementing the search_case_insensitive Function
Writing Error Messages to Standard Error Instead of Sta
ndard Output
Checking Where Errors Are Written
Printing Errors to Standard Error
Summary
CHAPTER 13: FUNCTIONAL LANGUAGE FEATURES: ITERATORS AND
CLOSURES
Closures: Anonymous Functions That Capture Their Enviro
nment
Capturing the Environment with Closures
Closure Type Inference and Annotation
Capturing References or Moving Ownership
Moving Captured Values Out of Closures and the Fn Tr
aits
Processing a Series of Items with Iterators
The Iterator Trait and the next Method
Methods That Consume the Iterator
Methods That Produce Other Iterators
Using Closures That Capture Their Environment
Improving Our I/O Project
Removing a clone Using an Iterator
Making Code Clearer with Iterator Adapters
Choosing Between Loops and Iterators
Comparing Performance: Loops vs. Iterators
Summary
CHAPTER 14: MORE ABOUT CARGO AND CRATES.IO
Customizing Builds with Release Profiles
Publishing a Crate to Crates.io
Making Useful Documentation Comments
Exporting a Convenient Public API with pub use
Setting Up a Crates.io Account
Adding Metadata to a New Crate
Publishing to Crates.io
Publishing a New Version of an Existing Crate
Deprecating Versions from Crates.io with cargo yank
Cargo Workspaces
Creating a Workspace
Creating the Second Package in the Workspace
Installing Binaries with cargo install
Extending Cargo with Custom Commands
Summary
CHAPTER 15: SMART POINTERS
Using Box<T> to Point to Data on the Heap
Using Box<T> to Store Data on the Heap
Enabling Recursive Types with Boxes
Treating Smart Pointers Like Regular References with De
ref
Following the Pointer to the Value
Using Box<T> Like a Reference
Defining Our Own Smart Pointer
Implementing the Deref Trait
Implicit Deref Coercions with Functions and Methods
How Deref Coercion Interacts with Mutability
Running Code on Cleanup with the Drop Trait
Rc<T>, the Reference Counted Smart Pointer
Using Rc<T> to Share Data
Cloning an Rc<T> Increases the Reference Count
RefCell<T> and the Interior Mutability Pattern
Enforcing Borrowing Rules at Runtime with RefCell<T>
Interior Mutability: A Mutable Borrow to an Immutabl
e Value
Allowing Multiple Owners of Mutable Data with Rc<T>
and RefCell<T>
Reference Cycles Can Leak Memory
Creating a Reference Cycle
Preventing Reference Cycles Using Weak<T>
Summary
CHAPTER 16: FEARLESS CONCURRENCY
Using Threads to Run Code Simultaneously
Creating a New Thread with spawn
Waiting for All Threads to Finish Using join Handles
Using move Closures with Threads
Using Message Passing to Transfer Data Between Threads
Channels and Ownership Transference
Sending Multiple Values and Seeing the Receiver Wait
ing
Creating Multiple Producers by Cloning the Transmitt
er
Shared-State Concurrency
Using Mutexes to Allow Access to Data from One Threa
d at a Time
Similarities Between RefCell<T>/Rc<T> and Mutex<T>/A
rc<T>
Extensible Concurrency with the Send and Sync Traits
Allowing Transference of Ownership Between Threads w
ith Send
Allowing Access from Multiple Threads with Sync
Implementing Send and Sync Manually Is Unsafe
Summary
CHAPTER 17: OBJECT-ORIENTED PROGRAMMING FEATURES
Characteristics of Object-Oriented Languages
Objects Contain Data and Behavior
Encapsulation That Hides Implementation Details
Inheritance as a Type System and as Code Sharing
Using Trait Objects That Allow for Values of Different
Types
Defining a Trait for Common Behavior
Implementing the Trait
Trait Objects Perform Dynamic Dispatch
Implementing an Object-Oriented Design Pattern
Defining Post and Creating a New Instance in the Dra
ft State
Storing the Text of the Post Content
Ensuring the Content of a Draft Post Is Empty
Requesting a Review Changes the Post’s State
Adding approve to Change the Behavior of content
Trade-offs of the State Pattern
Summary
CHAPTER 18: PATTERNS AND MATCHING
All the Places Patterns Can Be Used
match Arms
Conditional if let Expressions
while let Conditional Loops
for Loops
let Statements
Function Parameters
Refutability: Whether a Pattern Might Fail to Match
Pattern Syntax
Matching Literals
Matching Named Variables
Multiple Patterns
Matching Ranges of Values with ..=
Destructuring to Break Apart Values
Ignoring Values in a Pattern
Extra Conditionals with Match Guards
@ Bindings
Summary
CHAPTER 19: ADVANCED FEATURES
Unsafe Rust
Unsafe Superpowers
Dereferencing a Raw Pointer
Calling an Unsafe Function or Method
Accessing or Modifying a Mutable Static Variable
Implementing an Unsafe Trait
Accessing Fields of a Union
When to Use Unsafe Code
Advanced Traits
Associated Types
Default Generic Type Parameters and Operator Overloa
ding
Disambiguating Between Methods with the Same Name
Using Supertraits
Using the Newtype Pattern to Implement External Trai
ts
Advanced Types
Using the Newtype Pattern for Type Safety and Abstra
ction
Creating Type Synonyms with Type Aliases
The Never Type That Never Returns
Dynamically Sized Types and the Sized Trait
Advanced Functions and Closures
Function Pointers
Returning Closures
Macros
The Difference Between Macros and Functions
Declarative Macros with macro_rules! for General Met
aprogramming
Procedural Macros for Generating Code from Attribute
s
How to Write a Custom derive Macro
Attribute-Like Macros
Function-Like Macros
Summary
CHAPTER 20: FINAL PROJECT: BUILDING A MULTITHREADED WEB
SERVER
Building a Single-Threaded Web Server
Listening to the TCP Connection
Reading the Request
A Closer Look at an HTTP Request
Writing a Response
Returning Real HTML
Validating the Request and Selectively Responding
A Touch of Refactoring
Turning Our Single-Threaded Server into a Multithreaded
Server
Simulating a Slow Request
Improving Throughput with a Thread Pool
Graceful Shutdown and Cleanup
Implementing the Drop Trait on ThreadPool
Signaling to the Threads to Stop Listening for Jobs
Summary
APPENDIX A: KEYWORDS
Keywords Currently in Use
Keywords Reserved for Future Use
Raw Identifiers
APPENDIX B: OPERATORS AND SYMBOLS
Operators
Non-operator Symbols
APPENDIX C: DERIVABLE TRAITS
Debug for Programmer Output
PartialEq and Eq for Equality Comparisons
PartialOrd and Ord for Ordering Comparisons
Clone and Copy for Duplicating Values
Hash for Mapping a Value to a Value of Fixed Size
Default for Default Values
APPENDIX D: USEFUL DEVELOPMENT TOOLS
Automatic Formatting with rustfmt
Fix Your Code with rustfix
More Lints with Clippy
IDE Integration Using rust-analyzer
APPENDIX E: EDITIONS
INDEX
THE RUST PROGRAMMING LANGUAGE
2nd Edition
by Steve Klabnik and Carol Nichols, with
contributions from the Rust Community
THE RUST PROGRAMMING LANGUAGE, 2ND EDITION. Copyright ©
2023 by the Rust Foundation and the Rust Project Developers.
All rights reserved. No part of this work may be reproduced or transmitted in any
form or by any means, electronic or mechanical, including photocopying,
recording, or by any information storage or retrieval system, without the prior
written permission of the copyright owner and the publisher.
Printed in the United States of America
First printing
27 26 25 24 23 1 2 3 4 5
ISBN-13: 978-1-7185-0310-6 (print)
ISBN-13: 978-1-7185-0311-3 (ebook)
Publisher: William Pollock
Managing Editor: Jill Franklin
Production Manager: Sabrina Plomitallo-González
Production Editors: Jennifer Kepler and Katrina Horlbeck Olsen
Developmental Editor: Liz Chadwick
Cover Illustration: Karen Rustad Tölva
Interior Design: Octopod Studios
Technical Reviewer: JT
Copyeditor: Audrey Doyle
Compositor: Jeff Lytle, Happenstance Type-O-Rama
Proofreader: Liz Wheeler
For information on distribution, bulk sales, corporate sales, or translations, please
contact No Starch Press, Inc. directly at info@nostarch.com or:
No Starch Press, Inc.
245 8th Street, San Francisco, CA 94103
phone: 1.415.863.9900
www.nostarch.com
The Library of Congress has catalogued the first edition as follows:
Names: Klabnik, Steve, author. | Nichols, Carol, 1983- eauthor.
Title: The Rust programming language / by Steve Klabnik and Carol Nichols ; with
contributions from
the Rust Community.
Description: San Francisco : No Starch Press, Inc., 2018. | Includes index.
Identifiers: LCCN
2018014097 (print) | LCCN 2018019844 (ebook) | ISBN 9781593278519 (epub) | ISBN
1593278519 (epub)
| ISBN 9781593278281 (paperback) | ISBN 1593278284 (paperback)
Subjects: LCSH: Rust (Computer programming language) | BISAC: COMPUTERS /
Programming / Open Source.
| COMPUTERS / Programming Languages / General. | COMPUTERS / Programming /
General.
Classification: LCC QA76.73.R87 (ebook) | LCC QA76.73.R87 K53 2018 (print) | DDC
005.13/3--dc23
LC record available at https://lccn.loc.gov/2018014097
No Starch Press and the No Starch Press logo are registered trademarks of No
Starch Press, Inc. Other product and company names mentioned herein may be
the trademarks of their respective owners. Rather than use a trademark symbol
with every occurrence of a trademarked name, we are using the names only in an
editorial fashion and to the benefit of the trademark owner, with no intention of
infringement of the trademark.
The information in this book is distributed on an “As Is” basis, without warranty.
While every precaution has been taken in the preparation of this work, neither the
authors nor No Starch Press, Inc. shall have any liability to any person or entity
with respect to any loss or damage caused or alleged to be caused directly or
indirectly by the information contained in it.
About the Authors
Steve Klabnik was the lead for the Rust documentation team and
was one of Rust’s core developers. A frequent speaker and a prolific
open source contributor, he previously worked on projects such as
Ruby and Ruby on Rails.
Carol Nichols is a member of the Rust Crates.io Team and a former
member of the Rust Core Team. She’s a co-founder of Integer 32,
LLC, the world’s first Rust-focused software consultancy. Nichols has
also organized the Rust Belt Rust Conference.
About the Technical Reviewer
JT is a Rust core team member and the co-creator of the Rust error
message format, Rust Language Server (RLS), and Nushell. They
first started using Rust in 2011, and in 2016 joined Mozilla to work
on Rust full-time, helping to shape its direction for widespread use.
These days, they are a freelance Rust trainer and advocate for safe
systems programming.
FOREWORD
It wasn’t always so clear, but the Rust programming language is
fundamentally about empowerment: no matter what kind of code
you are writing now, Rust empowers you to reach further, to
program with confidence in a wider variety of domains than you did
before.
Take, for example, “systems-level” work that deals with low-level
details of memory management, data representation, and
concurrency. Traditionally, this realm of programming is seen as
arcane, accessible to only a select few who have devoted the
necessary years to learning it to avoid its infamous pitfalls. And even
those who practice it do so with caution, lest their code be open to
exploits, crashes, or corruption.
Rust breaks down these barriers by eliminating the old pitfalls and
providing a friendly, polished set of tools to help you along the way.
Programmers who need to “dip down” into lower-level control can do
so with Rust, without taking on the customary risk of crashes or
security holes and without having to learn the fine points of a fickle
toolchain. Better yet, the language is designed to guide you naturally
toward reliable code that is efficient in terms of speed and memory
usage.
Programmers who are already working with low-level code can use
Rust to raise their ambitions. For example, introducing parallelism
in Rust is a relatively low-risk operation: the compiler will catch the
classical mistakes for you. And you can tackle more aggressive
optimizations in your code with the confidence that you won’t
accidentally introduce crashes or vulnerabilities.
But Rust isn’t limited to low-level systems programming. It’s
expressive and ergonomic enough to make CLI apps, web servers,
and many other kinds of code quite pleasant to write—you’ll find
simple examples later in the book. Working with Rust allows you to
build skills that transfer from one domain to another; you can learn
Rust by writing a web app, then apply those same skills to target your
Raspberry Pi.
This book fully embraces the potential of Rust to empower its
users. It’s a friendly and approachable text intended to help you level
up not just your knowledge of Rust, but also your reach and
confidence as a programmer in general. So dive in, get ready to learn
—and welcome to the Rust community!
Nicholas Matsakis and Aaron Turon
PREFACE
This version of the text assumes you’re using Rust 1.62.0 (released
2022-06-30) or later with edition="2021" in the Cargo.toml file of all
projects to configure them to use Rust 2021 edition idioms. See
“Installation” on page 1 for instructions on installing or updating
Rust, and see Appendix E for information on editions.
The 2021 edition of the Rust language includes a number of
improvements that make Rust more ergonomic and that correct
some inconsistencies. On top of a general update to reflect these
improvements, this rendition of the book has a number of
improvements to address specific feedback:
Chapter 7 contains a new quick reference section on organizing
your code into multiple files with modules.
Chapter 13 has new and improved closure examples that more
clearly illustrate captures, the move keyword, and the Fn traits.
We fixed a number of small errors and imprecise wording
throughout the book. Thank you to the readers who reported
them!
Note that any code from earlier renditions of this book that
compiled will continue to compile with the relevant edition in the
project’s Cargo.toml, even as you update the Rust compiler version
you’re using. That’s Rust’s backward-compatibility guarantees at
work!
ACKNOWLEDGMENTS
We would like to thank everyone who has worked on the Rust
language for creating an amazing language worth writing a book
about. We’re grateful to everyone in the Rust community for being
welcoming and creating an environment worth welcoming more
folks into.
We’re especially thankful for everyone who read early versions of
this book online and provided feedback, bug reports, and pull
requests. Special thanks to Eduard-Mihai Burtescu, Alex Crichton,
and JT for providing technical review, and to Karen Rustad Tölva for
the cover art. Thank you to our team at No Starch, including Bill
Pollock, Liz Chadwick, and Janelle Ludowise, for improving this
book and bringing it to print.
Carol is grateful for the opportunity to work on this book. She
thanks her family for their constant love and support, especially her
husband, Jake Goulding, and her daughter, Vivian.
INTRODUCTION
Welcome to The Rust Programming
Language, an introductory book about
Rust. The Rust programming language
helps you write faster, more reliable
software. High-level ergonomics and low-level
control are often at odds in programming language
design; Rust challenges that conflict. Through
balancing powerful technical capacity and a great
developer experience, Rust gives you the option to
control low-level details (such as memory usage)
without all the hassle traditionally associated with
such control.
Who Rust Is For
Rust is ideal for many people for a variety of reasons. Let’s look at a
few of the most important groups.
Teams of Developers
Rust is proving to be a productive tool for collaborating among large
teams of developers with varying levels of systems programming
knowledge. Low-level code is prone to various subtle bugs, which in
most other languages can only be caught through extensive testing
and careful code review by experienced developers. In Rust, the
compiler plays a gatekeeper role by refusing to compile code with
these elusive bugs, including concurrency bugs. By working
alongside the compiler, the team can spend their time focusing on
the program’s logic rather than chasing down bugs.
Rust also brings contemporary developer tools to the systems
programming world:
Cargo, the included dependency manager and build tool, makes
adding, compiling, and managing dependencies painless and
consistent across the Rust ecosystem.
The rustfmt formatting tool ensures a consistent coding style
across developers.
The Rust Language Server powers integrated development
environment (IDE) integration for code completion and inline
error messages.
By using these and other tools in the Rust ecosystem, developers
can be productive while writing systems-level code.
Students
Rust is for students and those who are interested in learning about
systems concepts. Using Rust, many people have learned about
topics like operating systems development. The community is very
welcoming and happy to answer students’ questions. Through efforts
such as this book, the Rust teams want to make systems concepts
more accessible to more people, especially those new to
programming.
Companies
Hundreds of companies, large and small, use Rust in production for
a variety of tasks, including command line tools, web services,
DevOps tooling, embedded devices, audio and video analysis and
transcoding, cryptocurrencies, bioinformatics, search engines,
Internet of Things applications, machine learning, and even major
parts of the Firefox web browser.
Open Source Developers
Rust is for people who want to build the Rust programming
language, community, developer tools, and libraries. We’d love to
have you contribute to the Rust language.
People Who Value Speed and Stability
Rust is for people who crave speed and stability in a language. By
speed, we mean both how quickly Rust code can run and the speed at
which Rust lets you write programs. The Rust compiler’s checks
ensure stability through feature additions and refactoring. This is in
contrast to the brittle legacy code in languages without these checks,
which developers are often afraid to modify. By striving for zero-cost
abstractions—higher-level features that compile to lower-level code
as fast as code written manually—Rust endeavors to make safe code
be fast code as well.
The Rust language hopes to support many other users as well;
those mentioned here are merely some of the biggest stakeholders.
Overall, Rust’s greatest ambition is to eliminate the trade-offs that
programmers have accepted for decades by providing safety and
productivity, speed and ergonomics. Give Rust a try and see if its
choices work for you.
Who This Book Is For
This book assumes that you’ve written code in another programming
language, but doesn’t make any assumptions about which one. We’ve
tried to make the material broadly accessible to those from a wide
variety of programming backgrounds. We don’t spend a lot of time
talking about what programming is or how to think about it. If you’re
entirely new to programming, you would be better served by reading
a book that specifically provides an introduction to programming.
How to Use This Book
In general, this book assumes that you’re reading it in sequence from
front to back. Later chapters build on concepts in earlier chapters,
and earlier chapters might not delve into details on a particular topic
but will revisit the topic in a later chapter.
You’ll find two kinds of chapters in this book: concept chapters
and project chapters. In concept chapters, you’ll learn about an
aspect of Rust. In project chapters, we’ll build small programs
together, applying what you’ve learned so far. Chapter 2, Chapter 12,
and Chapter 20 are project chapters; the rest are concept chapters.
Chapter 1 explains how to install Rust, how to write a “Hello,
world!” program, and how to use Cargo, Rust’s package manager and
build tool. Chapter 2 is a hands-on introduction to writing a
program in Rust, having you build up a number-guessing game.
Here, we cover concepts at a high level, and later chapters will
provide additional detail. If you want to get your hands dirty right
away, Chapter 2 is the place for that. Chapter 3 covers Rust features
that are similar to those of other programming languages, and in
Chapter 4 you’ll learn about Rust’s ownership system. If you’re a
particularly meticulous learner who prefers to learn every detail
before moving on to the next, you might want to skip Chapter 2 and
go straight to Chapter 3, returning to Chapter 2 when you’d like to
work on a project applying the details you’ve learned.
Chapter 5 discusses structs and methods, and Chapter 6 covers
enums, match expressions, and the if let control flow construct. You’ll
use structs and enums to make custom types in Rust.
In Chapter 7, you’ll learn about Rust’s module system and about
privacy rules for organizing your code and its public application
programming interface (API). Chapter 8 discusses some common
collection data structures that the standard library provides, such as
vectors, strings, and hash maps. Chapter 9 explores Rust’s error-
handling philosophy and techniques.
Chapter 10 digs into generics, traits, and lifetimes, which give
you the power to define code that applies to multiple types. Chapter
11 is all about testing, which even with Rust’s safety guarantees is
necessary to ensure your program’s logic is correct. In Chapter 12,
we’ll build our own implementation of a subset of functionality from
the grep command line tool that searches for text within files. For
this, we’ll use many of the concepts we discussed in the previous
chapters.
Chapter 13 explores closures and iterators: features of Rust that
come from functional programming languages. In Chapter 14, we’ll
examine Cargo in more depth and talk about best practices for
sharing your libraries with others. Chapter 15 discusses smart
pointers that the standard library provides and the traits that enable
their functionality.
In Chapter 16, we’ll walk through different models of concurrent
programming and talk about how Rust helps you program in
multiple threads fearlessly. Chapter 17 looks at how Rust idioms
compare to object-oriented programming principles you might be
familiar with.
Chapter 18 is a reference on patterns and pattern matching,
which are powerful ways of expressing ideas throughout Rust
programs. Chapter 19 contains a smorgasbord of advanced topics
of interest, including unsafe Rust, macros, and more about lifetimes,
traits, types, functions, and closures.
In Chapter 20, we’ll complete a project in which we’ll implement
a low-level multithreaded web server!
Finally, some appendixes contain useful information about the
language in a more reference-like format. Appendix A covers Rust’s
keywords, Appendix B covers Rust’s operators and symbols,
Appendix C covers derivable traits provided by the standard
library, Appendix D covers some useful development tools, and
Appendix E explains Rust editions.
There is no wrong way to read this book: if you want to skip ahead,
go for it! You might have to jump back to earlier chapters if you
experience any confusion. But do whatever works for you.
An important part of the process of learning Rust is learning how
to read the error messages the compiler displays: these will guide you
toward working code. As such, we’ll provide many examples that
don’t compile along with the error message the compiler will show
you in each situation. Know that if you enter and run a random
example, it may not compile! Make sure you read the surrounding
text to see whether the example you’re trying to run is meant to
error. In most situations, we’ll lead you to the correct version of any
code that doesn’t compile.
Resources and How to Contribute to This Book
This book is open source. If you find an error, please don’t hesitate to
file an issue or send a pull request on GitHub at https://github.com/
rust-lang/book. Please see CONTRIBUTING.md at https://github.c
om/rust-lang/book/blob/main/CONTRIBUTING.md for more
details.
The source code for the examples in this book, errata, and other
information are available at https://nostarch.com/rust-programmi
ng-language-2nd-edition.
1
GETTING STARTED
Let’s start your Rust journey! There’s a
lot to learn, but every journey starts
somewhere. In this chapter, we’ll
discuss:
Installing Rust on Linux, macOS, and Windows
Writing a program that prints Hello, world!
Using cargo, Rust’s package manager and build system
Installation
The first step is to install Rust. We’ll download Rust through rustup, a
command line tool for managing Rust versions and associated tools.
You’ll need an internet connection for the download.
NOTE
If you prefer not to use rustup for some reason, please see the
Other Rust Installation Methods page at https://forge.rust-l
ang.org/infra/other-installation-methods.html for more
options.
The following steps install the latest stable version of the Rust
compiler. Rust’s stability guarantees ensure that all the examples in
the book that compile will continue to compile with newer Rust
versions. The output might differ slightly between versions because
Rust often improves error messages and warnings. In other words,
any newer, stable version of Rust you install using these steps should
work as expected with the content of this book.
COMMAND LINE NOTATION
In this chapter and throughout the book, we’ll show some
commands used in the terminal. Lines that you should enter in a
terminal all start with $. You don’t need to type the $
character; it’s the command line prompt shown to indicate the
start of each command. Lines that don’t start with $ typically
show the output of the previous command. Additionally,
PowerShell-specific examples will use > rather than $.
Installing rustup on Linux or macOS
If you’re using Linux or macOS, open a terminal and enter the
following command:
$ curl --proto '=https' --tlsv1.3 https://sh.rustup.rs -sSf | sh
The command downloads a script and starts the installation of the
rustup tool, which installs the latest stable version of Rust. You might
be prompted for your password. If the install is successful, the
following line will appear:
Rust is installed now. Great!
You will also need a linker, which is a program that Rust uses to
join its compiled outputs into one file. It is likely you already have
one. If you get linker errors, you should install a C compiler, which
will typically include a linker. A C compiler is also useful because
some common Rust packages depend on C code and will need a C
compiler.
On macOS, you can get a C compiler by running:
$ xcode-select --install
Linux users should generally install GCC or Clang, according to
their distribution’s documentation. For example, if you use Ubuntu,
you can install the build-essential package.
Installing rustup on Windows
On Windows, go to https://www.rust-lang.org/tools/install and
follow the instructions for installing Rust. At some point in the
installation, you’ll receive a message explaining that you’ll also need
the MSVC build tools for Visual Studio 2013 or later.
To acquire the build tools, you’ll need to install Visual Studio 2022
from https://visualstudio.microsoft.com/downloads. When asked
which workloads to install, include:
“Desktop Development with C++”
The Windows 10 or 11 SDK
The English language pack component, along with any other
language pack of your choosing
The rest of this book uses commands that work in both cmd.exe
and PowerShell. If there are specific differences, we’ll explain which
to use.
Troubleshooting
To check whether you have Rust installed correctly, open a shell and
enter this line:
$ rustc --version
You should see the version number, commit hash, and commit
date for the latest stable version that has been released, in the
following format:
rustc x.y.z (abcabcabc yyyy-mm-dd)
If you see this information, you have installed Rust successfully! If
you don’t see this information, check that Rust is in your %PATH%
system variable as follows.
In Windows CMD, use:
> echo %PATH%
In PowerShell, use:
> echo $env:Path
In Linux and macOS, use:
$ echo $PATH
If that’s all correct and Rust still isn’t working, there are a number
of places you can get help. Find out how to get in touch with other
Rustaceans (a silly nickname we call ourselves) on the community
page at https://www.rust-lang.org/community.
Updating and Uninstalling
Once Rust is installed via rustup, updating to a newly released version
is easy. From your shell, run the following update script:
$ rustup update
To uninstall Rust and rustup, run the following uninstall script from
your shell:
$ rustup self uninstall
Local Documentation
The installation of Rust also includes a local copy of the
documentation so that you can read it offline. Run rustup doc to open
the local documentation in your browser.
Any time a type or function is provided by the standard library and
you’re not sure what it does or how to use it, use the application
programming interface (API) documentation to find out!
Hello, World!
Now that you’ve installed Rust, it’s time to write your first Rust
program. It’s traditional when learning a new language to write a
little program that prints the text Hello, world! to the screen, so we’ll
do the same here!
NOTE
This book assumes basic familiarity with the command line.
Rust makes no specific demands about your editing or
tooling or where your code lives, so if you prefer to use an
integrated development environment (IDE) instead of the
command line, feel free to use your favorite IDE. Many IDEs
now have some degree of Rust support; check the IDE’s
documentation for details. The Rust team has been focusing
on enabling great IDE support via rust-analyzer. See Appendix
D for more details.
Creating a Project Directory
You’ll start by making a directory to store your Rust code. It doesn’t
matter to Rust where your code lives, but for the exercises and
projects in this book, we suggest making a projects directory in your
home directory and keeping all your projects there.
Open a terminal and enter the following commands to make a
projects directory and a directory for the “Hello, world!” project
within the projects directory.
For Linux, macOS, and PowerShell on Windows, enter this:
$ mkdir ~/projects
$ cd ~/projects
$ mkdir hello_world
$ cd hello_world
For Windows CMD, enter this:
> mkdir "%USERPROFILE%projects"
> cd /d "%USERPROFILE%projects"
> mkdir hello_world
> cd hello_world
Writing and Running a Rust Program
Next, make a new source file and call it main.rs. Rust files always
end with the .rs extension. If you’re using more than one word in
your filename, the convention is to use an underscore to separate
them. For example, use hello_world.rs rather than helloworld.rs.
Now open the main.rs file you just created and enter the code in Li
sting 1-1.
main.rs
fn main() {
println!("Hello, world!");
}
Listing 1-1: A program that prints Hello, world!
Save the file and go back to your terminal window in the
~/projects/hello_world directory. On Linux or macOS, enter the
following commands to compile and run the file:
$ rustc main.rs
$ ./main
Hello, world!
On Windows, enter the command .main.exe instead of ./main:
> rustc main.rs
> .main.exe
Hello, world!
Regardless of your operating system, the string Hello, world! should
print to the terminal. If you don’t see this output, refer back to
“Troubleshooting” on page 3 for ways to get help.
If Hello, world! did print, congratulations! You’ve officially written a
Rust program. That makes you a Rust programmer—welcome!
Anatomy of a Rust Program
Let’s review this “Hello, world!” program in detail. Here’s the first
piece of the puzzle:
fn main() {
}
These lines define a function named main. The main function is
special: it is always the first code that runs in every executable Rust
program. Here, the first line declares a function named main that has
no parameters and returns nothing. If there were parameters, they
would go inside the parentheses ().
The function body is wrapped in {}. Rust requires curly brackets
around all function bodies. It’s good style to place the opening curly
bracket on the same line as the function declaration, adding one
space in between.
NOTE
If you want to stick to a standard style across Rust projects,
you can use an automatic formatter tool called rustfmt to
format your code in a particular style (more on rustfmt in
Appendix D). The Rust team has included this tool with the
standard Rust distribution, as rustc is, so it should already be
installed on your computer!
The body of the main function holds the following code:
println!("Hello, world!");
This line does all the work in this little program: it prints text to
the screen. There are four important details to notice here.
First, Rust style is to indent with four spaces, not a tab.
Second, println! calls a Rust macro. If it had called a function
instead, it would be entered as println (without the !). We’ll discuss
Rust macros in more detail in Chapter 19. For now, you just need to
know that using a ! means that you’re calling a macro instead of a
normal function and that macros don’t always follow the same rules
as functions.
Third, you see the "Hello, world!" string. We pass this string as an
argument to println!, and the string is printed to the screen.
Fourth, we end the line with a semicolon (;), which indicates that
this expression is over and the next one is ready to begin. Most lines
of Rust code end with a semicolon.
Compiling and Running Are Separate Steps
You’ve just run a newly created program, so let’s examine each step
in the process.
Before running a Rust program, you must compile it using the
Rust compiler by entering the rustc command and passing it the
name of your source file, like this:
$ rustc main.rs
If you have a C or C++ background, you’ll notice that this is similar
to gcc or clang. After compiling successfully, Rust outputs a binary
executable.
On Linux, macOS, and PowerShell on Windows, you can see the
executable by entering the ls command in your shell:
$ ls
main main.rs
On Linux and macOS, you’ll see two files. With PowerShell on
Windows, you’ll see the same three files that you would see using
CMD. With CMD on Windows, you would enter the following:
> dir /B %= the /B option says to only show the file names =%
main.exe
main.pdb
main.rs
This shows the source code file with the .rs extension, the
executable file (main.exe on Windows, but main on all other
platforms), and, when using Windows, a file containing debugging
information with the .pdb extension. From here, you run the main or
main.exe file, like this:
$ ./main # or .main.exe on Windows
If your main.rs is your “Hello, world!” program, this line prints
Hello, world! to your terminal.
If you’re more familiar with a dynamic language, such as Ruby,
Python, or JavaScript, you might not be used to compiling and
running a program as separate steps. Rust is an ahead-of-time
compiled language, meaning you can compile a program and give the
executable to someone else, and they can run it even without having
Rust installed. If you give someone a .rb, .py, or .js file, they need to
have a Ruby, Python, or JavaScript implementation installed
(respectively). But in those languages, you only need one command
to compile and run your program. Everything is a trade-off in
language design.
Just compiling with rustc is fine for simple programs, but as your
project grows, you’ll want to manage all the options and make it easy
to share your code. Next, we’ll introduce you to the Cargo tool, which
will help you write real-world Rust programs.
Hello, Cargo!
Cargo is Rust’s build system and package manager. Most Rustaceans
use this tool to manage their Rust projects because Cargo handles a
lot of tasks for you, such as building your code, downloading the
libraries your code depends on, and building those libraries. (We call
the libraries that your code needs dependencies.)
The simplest Rust programs, like the one we’ve written so far,
don’t have any dependencies. If we had built the “Hello, world!”
project with Cargo, it would only use the part of Cargo that handles
building your code. As you write more complex Rust programs, you’ll
add dependencies, and if you start a project using Cargo, adding
dependencies will be much easier to do.
Because the vast majority of Rust projects use Cargo, the rest of
this book assumes that you’re using Cargo too. Cargo comes installed
with Rust if you used the official installers discussed in “Installation”
on page 1. If you installed Rust through some other means, check
whether Cargo is installed by entering the following in your terminal:
$ cargo --version
If you see a version number, you have it! If you see an error, such
as command not found, look at the documentation for your method of
installation to determine how to install Cargo separately.
Creating a Project with Cargo
Let’s create a new project using Cargo and look at how it differs from
our original “Hello, world!” project. Navigate back to your projects
directory (or wherever you decided to store your code). Then, on any
operating system, run the following:
$ cargo new hello_cargo
$ cd hello_cargo
The first command creates a new directory and project called
hello_cargo. We’ve named our project hello_cargo, and Cargo
creates its files in a directory of the same name.
Go into the hello_cargo directory and list the files. You’ll see that
Cargo has generated two files and one directory for us: a Cargo.toml
file and a src directory with a main.rs file inside.
It has also initialized a new Git repository along with a .gitignore
file. Git files won’t be generated if you run cargo new within an existing
Git repository; you can override this behavior by using cargo new --
vcs=git.
NOTE
Git is a common version control system. You can change cargo
new to use a different version control system or no version
control system by using the --vcs flag. Run cargo new --help to
see the available options.
Open Cargo.toml in your text editor of choice. It should look
similar to the code in Listing 1-2.
Cargo.toml
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/carg
o/reference/manifest.html
[dependencies]
Listing 1-2: Contents of Cargo.toml generated by cargo new
This file is in the TOML (Tom’s Obvious, Minimal Language)
format, which is Cargo’s configuration format.
The first line, [package], is a section heading that indicates that the
following statements are configuring a package. As we add more
information to this file, we’ll add other sections.
The next three lines set the configuration information Cargo needs
to compile your program: the name, the version, and the edition of
Rust to use. We’ll talk about the edition key in Appendix E.
The last line, [dependencies], is the start of a section for you to list
any of your project’s dependencies. In Rust, packages of code are
referred to as crates. We won’t need any other crates for this project,
but we will in the first project in Chapter 2, so we’ll use this
dependencies section then.
Now open src/main.rs and take a look:
src/main.rs
fn main() {
println!("Hello, world!");
}
Cargo has generated a “Hello, world!” program for you, just like
the one we wrote in Listing 1-1! So far, the differences between our
project and the project Cargo generated are that Cargo placed the
code in the src directory and we have a Cargo.toml configuration file
in the top directory.
Cargo expects your source files to live inside the src directory. The
top-level project directory is just for README files, license
information, configuration files, and anything else not related to your
code. Using Cargo helps you organize your projects. There’s a place
for everything, and everything is in its place.
If you started a project that doesn’t use Cargo, as we did with the
“Hello, world!” project, you can convert it to a project that does use
Cargo. Move the project code into the src directory and create an
appropriate Cargo.toml file.
Building and Running a Cargo Project
Now let’s look at what’s different when we build and run the “Hello,
world!” program with Cargo! From your hello_cargo directory, build
your project by entering the following command:
$ cargo build
Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 2.85 secs
This command creates an executable file in
target/debug/hello_cargo (or targetdebughello_cargo.exe on
Windows) rather than in your current directory. Because the default
build is a debug build, Cargo puts the binary in a directory named
debug. You can run the executable with this command:
$ ./target/debug/hello_cargo # or .targetdebughello_cargo.exe on Wind
ows
Hello, world!
If all goes well, Hello, world! should print to the terminal. Running
cargo build for the first time also causes Cargo to create a new file at
the top level: Cargo.lock. This file keeps track of the exact versions of
dependencies in your project. This project doesn’t have
dependencies, so the file is a bit sparse. You won’t ever need to
change this file manually; Cargo manages its contents for you.
We just built a project with cargo build and ran it with
./target/debug/hello_cargo, but we can also use cargo run to compile the
code and then run the resultant executable all in one command:
$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target/debug/hello_cargo`
Hello, world!
Using cargo run is more convenient than having to remember to run
cargo build and then use the whole path to the binary, so most
developers use cargo run.
Notice that this time we didn’t see output indicating that Cargo
was compiling hello_cargo. Cargo figured out that the files hadn’t
changed, so it didn’t rebuild but just ran the binary. If you had
modified your source code, Cargo would have rebuilt the project
before running it, and you would have seen this output:
$ cargo run
Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 0.33 secs
Running `target/debug/hello_cargo`
Hello, world!
Cargo also provides a command called cargo check. This command
quickly checks your code to make sure it compiles but doesn’t
produce an executable:
$ cargo check
Checking hello_cargo v0.1.0 (file:///projects/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs
Why would you not want an executable? Often, cargo check is much
faster than cargo build because it skips the step of producing an
executable. If you’re continually checking your work while writing
the code, using cargo check will speed up the process of letting you
know if your project is still compiling! As such, many Rustaceans run
cargo check periodically as they write their program to make sure it
compiles. Then they run cargo build when they’re ready to use the
executable.
Let’s recap what we’ve learned so far about Cargo:
We can create a project using cargo new.
We can build a project using cargo build.
We can build and run a project in one step using cargo run.
We can build a project without producing a binary to check for
errors using cargo check.
Instead of saving the result of the build in the same directory as
our code, Cargo stores it in the target/debug directory.
An additional advantage of using Cargo is that the commands are
the same no matter which operating system you’re working on. So, at
this point, we’ll no longer provide specific instructions for Linux and
macOS versus Windows.
Building for Release
When your project is finally ready for release, you can use cargo build
--release to compile it with optimizations. This command will create
an executable in target/release instead of target/debug. The
optimizations make your Rust code run faster, but turning them on
lengthens the time it takes for your program to compile. This is why
there are two different profiles: one for development, when you want
to rebuild quickly and often, and another for building the final
program you’ll give to a user that won’t be rebuilt repeatedly and that
will run as fast as possible. If you’re benchmarking your code’s
running time, be sure to run cargo build --release and benchmark with
the executable in target/release.
Cargo as Convention
With simple projects, Cargo doesn’t provide a lot of value over just
using rustc, but it will prove its worth as your programs become more
intricate. Once programs grow to multiple files or need a
dependency, it’s much easier to let Cargo coordinate the build.
Even though the hello_cargo project is simple, it now uses much of
the real tooling you’ll use in the rest of your Rust career. In fact, to
work on any existing projects, you can use the following commands
to check out the code using Git, change to that project’s directory,
and build:
$ git clone example.org/someproject
$ cd someproject
$ cargo build
For more information about Cargo, check out its documentation at
https://doc.rust-lang.org/cargo.
Summary
You’re already off to a great start on your Rust journey! In this
chapter, you’ve learned how to:
Install the latest stable version of Rust using rustup
Update to a newer Rust version
Open locally installed documentation
Write and run a “Hello, world!” program using rustc directly
Create and run a new project using the conventions of Cargo
This is a great time to build a more substantial program to get used
to reading and writing Rust code. So, in Chapter 2, we’ll build a
guessing game program. If you would rather start by learning how
common programming concepts work in Rust, see Chapter 3 and
then return to Chapter 2.
2
PROGRAMMING A GUESSING GAME
Let’s jump into Rust by working
through a hands-on project together!
This chapter introduces you to a few
common Rust concepts by showing you
how to use them in a real program. You’ll learn about
let, match, methods, associated functions, external
crates, and more! In the following chapters, we’ll
explore these ideas in more detail. In this chapter,
you’ll just practice the fundamentals.
We’ll implement a classic beginner programming problem: a
guessing game. Here’s how it works: the program will generate a
random integer between 1 and 100. It will then prompt the player to
enter a guess. After a guess is entered, the program will indicate
whether the guess is too low or too high. If the guess is correct, the
game will print a congratulatory message and exit.
Setting Up a New Project
To set up a new project, go to the projects directory that you created
in Chapter 1 and make a new project using Cargo, like so:
$ cargo new guessing_game
$ cd guessing_game
The first command, cargo new, takes the name of the project
(guessing_game) as the first argument. The second command changes to
the new project’s directory.
Look at the generated Cargo.toml file:
Cargo.toml
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo
/reference/manifest.html
[dependencies]
As you saw in Chapter 1, cargo new generates a “Hello, world!”
program for you. Check out the src/main.rs file:
src/main.rs
fn main() {
println!("Hello, world!");
}
Now let’s compile this “Hello, world!” program and run it in the
same step using the cargo run command:
$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 1.50s
Running `target/debug/guessing_game`
Hello, world!
The run command comes in handy when you need to rapidly iterate
on a project, as we’ll do in this game, quickly testing each iteration
before moving on to the next one.
Reopen the src/main.rs file. You’ll be writing all the code in this
file.
Processing a Guess
The first part of the guessing game program will ask for user input,
process that input, and check that the input is in the expected form.
To start, we’ll allow the player to input a guess. Enter the code in List
ing 2-1 into src/main.rs.
src/main.rs
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {guess}");
}
Listing 2-1: Code that gets a guess from the user and prints it
This code contains a lot of information, so let’s go over it line by
line. To obtain user input and then print the result as output, we
need to bring the io input/output library into scope. The io library
comes from the standard library, known as std:
use std::io;
By default, Rust has a set of items defined in the standard library
that it brings into the scope of every program. This set is called the
prelude, and you can see everything in it at https://doc.rust-lang.or
g/std/prelude/index.html.
If a type you want to use isn’t in the prelude, you have to bring that
type into scope explicitly with a use statement. Using the std::io
library provides you with a number of useful features, including the
ability to accept user input.
As you saw in Chapter 1, the main function is the entry point into
the program:
fn main() {
The fn syntax declares a new function; the parentheses, (), indicate
there are no parameters; and the curly bracket, {, starts the body of
the function.
As you also learned in Chapter 1, println! is a macro that prints a
string to the screen:
println!("Guess the number!");
println!("Please input your guess.");
This code is printing a prompt stating what the game is and
requesting input from the user.
Storing Values with Variables
Next, we’ll create a variable to store the user input, like this:
let mut guess = String::new();
Now the program is getting interesting! There’s a lot going on in
this little line. We use the let statement to create the variable. Here’s
another example:
let apples = 5;
This line creates a new variable named apples and binds it to the
value 5. In Rust, variables are immutable by default, meaning once
we give the variable a value, the value won’t change. We’ll be
discussing this concept in detail in “Variables and Mutability” on
page 32. To make a variable mutable, we add mut before the variable
name:
Random documents with unrelated
content Scribd suggests to you:
The Rust Programming Language Second Edition 2 Converted Steve Klabnik
The Rust Programming Language Second Edition 2 Converted Steve Klabnik
The Rust Programming Language Second Edition 2 Converted Steve Klabnik
The Project Gutenberg eBook of Duell-Codex
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.
Title: Duell-Codex
Author: Gustav Hergsell
Release date: March 26, 2017 [eBook #54438]
Most recently updated: October 23, 2024
Language: German
Credits: Produced by Harry Lamé and the Online Distributed
Proofreading Team at http://www.pgdp.net (This file
was
produced from images generously made available by
The
Internet Archive)
*** START OF THE PROJECT GUTENBERG EBOOK DUELL-CODEX
***
Anmerkungen zur Transkription
befinden sich am Ende dieses
Textes.
DUELL-CODEX.
ZWEITE, ERGÄNZTE AUFLAGE.
DUELL-CODEX.
VON
GUSTAV HERGSELL
K. K. HAUPTMANN i. E., DIRECTOR DER KÖNIGL. LANDES-FECHTSCHULE
ZU PRAG, RITTER DES KAISERL. OESTERREICH. FRANZ JOSEFS-ORDENS,
DES KÖNIGL. SÄCHSISCHEN ALBRECHT-ORDENS I. CL., DES KÖNIGL.
WÜRTTEMBERGISCHEN FRIEDRICH-ORDENS I. CL., DES SACHSEN
ERNESTI-NISCHEN HAUSORDENS I. CL., BESITZER DES HERZOGL.
SACHSEN-COBURG-GOTHA’SCHEN VERDIENST-ORDENS ERNST I. FÜR
KUNST U. WISSENSCHAFT.
ZWEITE, ERGÄNZTE AUFLAGE.
MIT 7 TAFELN.
WIEN. PEST. LEIPZIG.
A. HARTLEBEN’S VERLAG.
1897.
Alle Rechte vorbehalten.
K. u. k. Hofbuchdruckerei Carl Fromme in Wien.
Vorwort zur ersten Auflage.
Das von meinen Schülern und vielen Freunden der Fechtkunst
oft an mich gestellte Ersuchen, eine übersichtliche
Zusammenstellung der Duellregeln zu verfassen und den Vorgang
bei einem Ernstfalle kurz und bündig zu schildern, hat mich
bewogen, die Ergebnisse meiner Beobachtungen und meines
Studiums über diesen Gegenstand in dem vorliegenden Werke
niederzulegen.
Ich habe mich bei dieser Arbeit durch die Aufzeichnungen des
Grafen Chatauvillard, seiner Mitarbeiter und Nachfolger, deren ich
gegebenenfalls Erwähnung thue, leiten lassen; ich habe getrachtet,
die dort veröffentlichten Vorschriften, von denen einige die Sache
bloss streifen, für die gegenwärtigen Verhältnisse manchmal nicht
mehr recht verständlich oder unvollendet sind, zu entwickeln, zu
präcisiren und nach Möglichkeit zu vervollständigen.
Wenngleich in den Einzelnheiten veraltet, bieten die von
Chatauvillard aufgestellten Regeln, Vorschriften und Ansichten
dennoch ein unschätzbares Material, und werden von allen Männern
von Ehre respectirt, so lange nicht eine berufene Vereinigung von
Ehrenmännern andere Vorschriften oder Gesetze verfasst.
Zu allen Zeiten bis in die letzten Jahre haben sich nicht wenig
Schriftsteller der undankbaren Aufgabe bemächtigt, gegen die
Nothwendigkeit und die Gebräuche des Duelles aufzutreten, indem
sie das Duell von dem dreifachen Gesichtspunkte: der Vernunft, der
Moral und der gesellschaftlichen Sitten, zu beleuchten versuchten.
Von der Wahrheit des Satzes: „Es giebt nur ein Mittel, das Duell
abzuschaffen — man schaffe das Ehrgefühl ab” durchdrungen, habe
ich bei der mir gestellten Aufgabe grundsätzlich alle Betrachtungen
über das Duell beiseite gelassen und mich darauf beschränkt, im I.
Theile die Vorschriften oder Gesetze des Duelles zusammenzufassen
und im II. Theile den Vorgang im Terrain beim Kampfe selbst, in
logischer Reihenfolge zu schildern.
Nur ungern unterzog ich mich auf vielfachen Wunsch der
Aufgabe, in einem III. Theile eine Schilderung der irregulären,
sogenannten Ausnahmsduelle zu geben.
Der Ursprung und die geschichtliche Entwickelung des Duelles
wurde nicht berührt, weil beides nicht zur Sache gehört; Fragen über
das Verhalten während des Kampfes selbst, gegenüber Fechtern
oder Naturalisten, über Offensive oder Defensive, wurden nur so
weit erörtert, als deren Behandlung bei Schilderung des Kampfes
unausweichlich war.
Was die Bezeichnung der von den Duellanten gewählten
Vertreter als Zeugen oder Secundanten anbelangt, so darf ich wohl
als bekannt voraussetzen, dass es ehedem einen Unterschied
zwischen Zeugen und Secundanten gab. Diese waren in der Zeit des
Ritterthums Kampfgenossen und hatten als solche wieder ihre
Zeugen.
Heute giebt es streng genommen nur Zeugen; diesen Namen
führen auch die Vertreter der Gegner in Frankreich. In Deutschland
werden beide Bezeichnungen abwechselnd gebraucht; bei uns in
Oesterreich heissen die Vertrauensträger der Gegner fast allgemein
Secundanten. Dieser Gepflogenheit habe auch ich mich
angeschlossen.
Wenn auch bei den einzelnen Arten des Zweikampfes die
vorbereitenden Schritte im Terrain stets gleich sind und bei
Darstellung derselben auf die allgemeinen Vorschriften verwiesen
werden konnte, so fand ich mich dennoch veranlasst, um jede
Duellart für sich allein in ihrer Entwickelung zu schildern, dieser
allgemeinen Vorschriften stets in Kurzem zu erwähnen, wodurch
einzelne Wiederholungen unvermeidlich waren.
Weit entfernt, dass dieser Codex eine Aufmunterung zu
unnöthigen, muthwilligen Duellen werde, soll er vielmehr allen
Jenen, die durch die Umstände gezwungen sind, sich zu einer
bewaffneten Begegnung zu stellen, als Richtschnur darüber dienen,
wozu sie berechtigt und verpflichtet sind, andererseits aber Alle, die
durch Vertrauen berufen werden, bei dem Kampfe zu interveniren,
aber wenig Erfahrung für solche Vorgänge haben, lehren, dass es
mitunter in ihrer Macht steht, ungünstige Wechselfälle des Kampfes
bei vollkommener Wahrung der Ehre Dessen, den sie vertreten, zu
verringern, wenn nicht hintanzuhalten.
Ist es mir gelungen, das mir gesteckte Ziel zu erreichen, so ist
mein Zweck erfüllt.
In dieser Erwartung übergebe ich hiermit das vorliegende Werk
der Oeffentlichkeit.
Der Verfasser.
Vorwort zur zweiten Auflage.
Auf Grund der Erfahrungen, welche ich seit Ausgabe der ersten
Auflage gemacht habe, sowie in Folge der mannigfachen an mich
gestellten Anfragen in Beilegung und Austragung von
Ehrenangelegenheiten, die ich alle nach Thunlichkeit zu
berücksichtigen trachtete, wurden in dieser zweiten Auflage, speciell
im ersten Theile jene Artikel einer gründlichen Bearbeitung durch
Ergänzungen unterzogen, die ich zur rascheren Orientirung für
besonders nothwendig erachtete.
Besitzer der ersten Auflage werden in dieser neuen Ausgabe
wesentliche Ergänzungen finden, die ihnen als weiterer Behelf zur
Schlichtung von Ehrenangelegenheiten von Nutzen sein dürften.
An dieser Stelle wollen wir auch des neueren französischen
Fachschriftstellers A. Croabbon erwähnen, dessen interessantes
Werk: „La science de point d’honneur” wir gegebenenfalls bei
unseren Ergänzungen anführen.
Bei dieser Gelegenheit sei nochmals darauf hingewiesen, dass
die Bildtafeln lediglich für die Secundanten bestimmt sind.
P r a g .
Der Verfasser.
EHRE DEN WAFFEN!
I N H A L T .
Seite
Vorwort zur ersten Auflage V
Vorwort zur zweiten Auflage VIII
Einleitung 3
I. Theil.
Von den Duellregeln im Allgemeinen 8
Vom Duell und der Beleidigung 11
Directe Beleidigung 13
Beleidigung ersten Grades 14
Einfache Beleidigung 14
Beleidigung zweiten Grades 15
Beleidigung durch Beschimpfung 15
Beleidigung dritten Grades 16
Beleidigung durch Schlag 16
Beleidigung durch ungerechte Beschuldigung 18
Grundlose Herausforderung 20
Indirecte Beleidigung 22
Rechte des Beleidigten und deren Zuerkennung 23
a) Beleidigung einer Person 23
b) Beleidigung einer Familie oder einer Corporation 26
Pflichten des Beleidigers 27
Die Forderung 28
Secundanten und ihre Pflichten 33
Beilegung des Duelles 51
Ablehnung des Duelles 53
Gänzliche Ablehnung 54
An- oder Aberkennung der Satisfactionsfähigkeit durch
einen Ehrenrath 58
Ehrenrath 60
Ablehnung einer bestimmten Duellart 62
Säbel oder Degen 62
Pistole 64
Stellvertretung und Verantwortlichkeit für Andere 65
Unfähigkeit oder Ausschliessung der Secundanten 69
Unterbrechung des Kampfes 71
Haltruf 71
Pause 75
Desarmirung 77
An die Wand drängen 79
Verletzung der Duellgesetze 81
Leibesvisitirung 83
Die Verwundung 84
Parade oder Opposition mit der linken Hand 88
Der Kampf 90
Austragung des Duelles 97
Nach dem Kampfe 99
Von den Ausnahmsduellen 101
II. Theil.
Duellarten 108
Säbelduell 113
Beschaffenheit der Waffen 113
Bekleidung 114
Arten des Säbelduelles 116
I. Säbelduell ohne Stoss 116
Vorgang auf dem Terrain 117
II. Säbelduell mit Stoss 129
Degenduell 129
Beschaffenheit der Waffen 129
Bekleidung 130
Vorgang auf dem Terrain 131
Pistolenduelle 143
Beschaffenheit der Waffen 150
Arten der Pistolenduelle 151
Bekleidung 152
Vorgang auf dem Terrain 153
I. Pistolenduell mit festem Standpunkte 153
II. Pistolenduell mit festem Standpunkte und freiem
Schusse 160
III. Pistolenduell mit Vorrücken. — Barrièren 165
IV. Pistolenduell mit unterbrochenem Vorrücken 171
V. Pistolenduell auf parallelen Linien 175
VI. Pistolenduell auf Commando oder Signal 179
Revolver 186
III. Theil.
Ausnahmsduelle 189
Arten des Ausnahmsduelles 191
Ausnahmsduell mit Pistolen 192
I. Pistolenduell mit festem Standpunkte bei geringerer
als der gesetzmässig kürzesten Entfernung 192
II. Pistolenduell mit Vorrücken 195
Mit enger oder naher Barrière 195
Mit einer Barrière 196
III. Duell mit e i n e r geladenen Pistole 196
IV. Pistolenduell auf parallelen Linien mit
ununterbrochenem Vorrücken 200
Kampf mit Gewehr 204
Kampf mit Carabiner 205
Kampf zu Pferde 205
Amerikanisches Duell 206
Anhang.
Muster für die Abfassung von Protokollen 211
I.
Schriftliche Vereinbarung der Secundanten 211
A. Bei Beleidigung ersten Grades 213
B. Beilegung des Duelles nach einer Beschimpfung 214
II.
Protokoll über den stattgefundenen Zweikampf 216
VERZEICHNIS DER TAFELN.
Seite
I. Säbelduell 115
II. Degenduell 128
III. Pistolenduell mit festem Standpunkte 153
IV. Pistolenduell mit festem Standpunkte und freiem
Schusse 160
V. Pistolenduell mit Vorrücken. — Barrièren 165
VI. Pistolenduell mit unterbrochenem Vorrücken 171
VII. Pistolenduell auf parallelen Linien 175
DUELL-CODEX.
EINLEITUNG.
Der Zweikampf steht ausserhalb des Gesetzes, keine seiner
Regeln kann den Charakter der Legalität in der gewöhnlichen
Auffassung dieses Wortes beanspruchen. Dennoch zögern wir nicht,
jenen Regeln den Namen „Duellcodex” beizulegen.
Wenn es wahr ist, was thatsächlich unter allen civilisirten
Völkern mit Recht zugegeben wird, dass die Ehre ebenso
unantastbar ist wie die Gesetze, so sind die Vorschriften über die
zum Schutze der gekränkten Ehre zu beobachtenden Vorgänge von
keinem geringeren Ansehen als jene.
Der Grund, dass die staatlichen Gesetze den Zweikampf
ausserhalb ihres Rahmens verweisen, liegt in der Unzulässigkeit der
Selbsthilfe. An deren Stelle ist in einem geordneten Gemeinwesen
die staatliche Hilfe gesetzt, damit der Schwache nicht Unrecht
erdulden müsse von dem Starken.
Allein ganz abgesehen davon, dass die Selbsthilfe nicht überall
verwerflich ist, wie uns die Zulässigkeit der Nothwehr und des
Besitzschutzes bezeugen, ist nicht zu übersehen, dass die Gesetze
Männern mit hochentwickeltem Ehrgefühl nach deren Ueberzeugung
bisweilen nicht ausreichenden Schutz gegen ihnen selbst oder ihnen
nahestehenden Personen widerfahrenen Unbilden gewähren.
Von diesem Standpunkte erscheint daher das Duell weder
anormal, noch unbegreiflich, noch unmoralisch.
„Jeder,” sagt uns Graf Chatauvillard, „ist der herben
Nothwendigkeit unterworfen, sein Leben zu wagen, um wegen einer
Beleidigung oder Beschimpfung Rechenschaft zu verlangen.”
Die Sache ist daher nach der Meinung desselben Autors im
menschlichen Leben wichtig genug, um im Vorhinein nach
Unparteilichkeit und Ehrgefühl geordnet zu werden, zumal die sich
täglich erneuernden Beispiele das Bedürfnis darnach erweisen.
So werden diese Regeln zum Schutze für Alle als Schranken
wider Ueberfall und Rachsucht und können selbst als ein Ausfluss
der Cultur und ritterlicher Gesittung angesehen werden, welche die
Feststellung derselben als begründet erscheinen lässt.
Diese Vorschriften haben sich aus dem Herkommen, dem
Gebrauche und aus der Ueberzeugung gleichgesinnter Kreise von
der Nothwendigkeit dieses Gebrauches herausgebildet, beruhen also
auf denselben rechtserzeugenden Grundlagen wie das
Gewohnheitsrecht.
Einzig und allein in diesem eingeschränkten Sinne betrachtet
man jene Duellarten, die den herkömmlichen Vorschriften
entsprechen, als „legale”. Wird hiervon auch nur in einzelnen
Punkten abgewichen, so steht das Duell auch ausserhalb des
Herkommens und heisst „Ausnahmsduell” (exceptionelles Duell).
Graf Chatauvillard, Mitglied des Pariser Jockey-Club, hat in Folge
einer an ihn gerichteten Aufforderung im Vereine der weiteren
Mitglieder General Graf Excelmans, Grafen du Hallay-Coëtquen,
General Baron Gourgaud, Brivois und des Vicomte de Contades sich
der Aufgabe unterzogen, die Gebräuche und Vorschriften des Duelles
zu fixiren, die unter dem Titel „Essai sur le duel” im Jahre 1836 zu
Paris erschienen.
Dieses Werk wurde nicht nur in Paris von der öffentlichen
Meinung lebhaft begrüsst, sondern jene Vorschriften haben sich
auch bald ausserhalb Frankreich Geltung verschafft, da sie durch die
Signatur hervorragender Mitglieder der Pariser Gesellschaft
sanctionirt wurden.
Ueberzeugt, dass es von allgemeinem Interesse sein dürfte, die
Namen dieser Mitarbeiter kennen zu lernen, wollen wir dieselben
anführen.
Die Unterschrift wurde mit folgenden Worten eingeleitet:
„Innig überzeugt, dass die Intentionen des Verfassers, weit
entfernt die Duelle zu protegiren, im Gegentheil dahin streben, ihre
Zahl zu vermindern, sie zu regeln und ihren verderblichen Charakter
zu verringern, geben die Unterzeichneten den in diesem Werke
aufgestellten und auseinandergesetzten Vorschriften ihre volle
Genehmigung.”
Marschall Graf de Lobau, Pair von Frankreich.
Marschall Graf Molitor, Pair von Frankreich.
Viceadmiral Marquis de Sercey, Pair von Frankreich.
Generallieutenant Herzog de Guiche.
Generallieutenant Graf Dutaillis, Pair von Frankreich.
Generallieutenant Herzog de Doudeauville.
Generallieutenant Graf de la Grange, Pair von Frankreich.
Generallieutenant Vicomte de Cavaignac.
General de Fourolles.
Generallieutenant Graf de la Houssay.
General Graf Friaut.
Generallieutenant Baron Billard.
Generallieutenant Graf Claparède, Pair von Frankreich.
General Graf Clary.
General Miot.
General A. de Saint-Yon.
Generallieutenant Pierre Boyer.
General L. Bernard.
Generallieutenant Graf Merlin.
Generallieutenant Graf Villaret de Joyeuse.
Generallieutenant de Solignac.
General Vicomte de Maucomble.
Generallieutenant Baron Gourgaud.
Generallieutenant Excelmans, Pair von Frankreich.
Oberst de Rossi.
Oberst L. Brack.
Oberst de Garaube.
Oberstlieutenant Graf de Maussion.
Oberstlieutenant R. de Grandmont.
Oberstlieutenant J. Combe.
Oberstlieutenant de Casanova.
Oberstlieutenant de Lherminier.
Oberstlieutenant Baron E. de Marguerittes.
Oberst der Nationalgarde Graf de Lariboissière, Pair von
Frankreich.
Oberst der Nationalgarde Le Mercier.
Herzog d’Istrie, Pair von Frankreich.
Herzog de Saulx Tavannes, Pair von Frankreich.
Prinz Alex. de Wagram, Pair von Frankreich.
Escadronschef Graf von Sercey.
Capitaine Graf von Grabowski.
Louis Paira.
Prinz Poniatowski.
Graf de Plaisance.
Vicomte Daure.
Marquis de Bellemont.
Vicomte Curial.
Graf de Montholon.
Vicomte Walch.
De Messimieux.
Commandant Graf Ch. de Nieuwerkerke.
Du Suau de la Croix.
Capitaine Marquis de Livry.
G. de Martignac.
Gaetan Murat.
Graf von Pontcarré.
Marquis de Quémadeuc.
Ed. Faye.
Baron d’Aubigny.
Capitaine Graf Walewsky.
Ed. Adam.
Capitaine E. d’Hervas.
G. de la Rifaudière.
Graf de Clermont-Mont-Saint-Jean.
Capitaine Graf de Clerembault.
Graf de Langle.
Merle.
Vicomte Dutaillis.
Commandant Graf de Walewski.
A. Dufougerais.
Phil. Martines.
M. Delaunay.
Graf J. de la Grange.
Baron de Préjan.
Brivois.
Vicomte de Contades.
Graf du Hallay-Coëtquen.
Zum Schlusse findet sich die Bemerkung:
„Der Herr Kriegsminister, die Herren Präfecten etc. etc. haben
als Männer das gebilligt, was sie als Beamte nicht unterzeichnen
konnten.”
I. Theil.
Von den Duellregeln im
Allgemeinen.
Vom Duell und der Beleidigung.
Jedes Wort, jede Schrift, Absicht oder Geste, welche die
Eigenliebe, Zartgefühl oder Ehre eines Zweiten verletzt, ist für diesen
eine Beleidigung.
Die Nuancen der Beleidigungen gehen ins Unendliche; es lässt
sich der Werth derselben schwer feststellen, es wird schwierig, die
verschiedenen Beleidigungen zu definiren.
Die Beleidigung ist Gefühlssache, denn jeder fühlt auf
verschiedene Art und Weise; dies hängt meist mit der socialen
Stellung zusammen.
Wenn aber eine Eintheilung, eine Beurtheilung der Beleidigung
stattfinden soll, dann hat diese in der Weise vorgenommen zu
werden, dass die entehrende Beschimpfung, und vor allem der
Schlag, abgesondert wird.
Um sich für eine Beleidigung Genugthuung zu verschaffen, um
den Angriff gegen seine Person zurückzuweisen, greift man zu den
Waffen — erfolgt das Duell.
Man schlägt sich, um für eine Beleidigung persönlich
Genugthuung zu geben oder diese zu erhalten.
Erfolgt die Beleidigung ohne Grund, so ist dies allerdings ein
beklagenswerther Umstand, und das Unrecht ist auf Seite des
Provocirenden, aber er allein hat sich hierüber Rechenschaft zu
geben; um dieses Unrecht zu sühnen, setzt er im Waffengange, im
Duell, sein Leben ein.
Der Beweggrund, durch welchen das Duell — der Zweikampf —
herbeigeführt wurde, ist gleichgiltig.
Das Duell ist demnach ein zwischen zwei Personen
stattfindender verabredeter Kampf, welche in diesem, also durch
Hilfenahme der Waffen, das Mittel suchen, ausserhalb des Gesetzes
eine Differenz zu begleichen, oder sich durch diese Gerechtigkeit zu
verschaffen.
Es ist ein auf Basis gesetzmässiger Regeln und vorher
getroffener Vereinbarungen, in Gegenwart von Zeugen, mit
g l e i c h a r t i g e n , t ö d t l i c h e n Waffen stattfindender
Zweikampf.
Wenn daher die beiden Gegner das Uebereinkommen getroffen
haben, gleichgiltig ob ausdrücklich oder stillschweigend, den
Gesetzen der Ehre nur scheinbar Genüge zu leisten — entweder auf
Zeitdauer sich der blanken Waffen zu bedienen, ohne ernstlich
angreifen zu wollen, oder beiderseits bei einem Pistolenduell in die
Luft zu schiessen u. s. w. — so ist dieses kein Zweikampf, kein Duell.
Die gesetzmässigen Regeln verlangen g l e i c h a r t i g e Waffen,
damit nicht im Vorhinein der Sieg zu Gunsten des einen oder des
anderen der beiden Combattanten entschieden wird.
Aus diesem erhellt, dass den beiden Gegnern auch die
Möglichkeit geboten werden muss, durch ihr gegenseitiges Einsetzen
von Kraft und Geschicklichkeit aus dem Kampfe als Sieger
hervorgehen zu können.
Es kann daher in bestimmten Fällen die Ablehnung einer
bestimmten Duellart stattfinden.
So steht bei gewissen Graden der Beleidigung den Secundanten
das Recht zu, die Annahme eines Säbel- oder Degenduelles zu
verweigern, falls der rechte Arm ihres Clienten derart strupirt ist,
dass der freie Gebrauch der Waffe gehindert erscheint; ebenso
können die Secundanten eines Einäugigen ein Pistolenduell
verweigern.
Weiters verlangt das Gesetz t ö d t l i c h e Waffen.
Ein Kampf mit „tödtlichen” Waffen liegt nicht vor, wenn die
Waffen im Vorhinein eine ernste Verwundung ausschliessen, oder die
Combattanten derartige Schutzmassregeln in Anwendung bringen,
die eine schwere, lebensgefährliche Verwundung nicht zulassen.
Es ist daher ein Faustkampf ebenso wenig ein Zweikampf — ein
Duell — wie das Boxen der Engländer.
Aber auch die Waffen müssen den hergebrachten Sitten, den
Duellgesetzen entsprechen. Messer, Dolche, Handschare, Lanzen
sind ebenso wenig Duellwaffen, wie Stöcke oder dergleichen
ähnliche, für einen Ueberfall oder für die Nothwehr bestimmte
Waffen.
Erfolgt der Kampf mit beiderseitiger Uebereinstimmung auf der
Stelle, oder auch später, mit oder ohne vorher gepflogenen
Vereinbarungen, aber ohne Zeugen oder Secundanten, so wird
dieser Zweikampf weder von der öffentlichen Meinung, noch vor
dem Gesetze als ein legales Duell angesehen.
Dieses Zusammentreffen führt den Namen Rencontre.
Der Kampf muss ein auf Basis vorher getroffener
Vereinbarungen verabredeter sein, wobei es gleichgiltig erscheint, ob
den Vereinbarungen längere oder kürzere Verhandlungen zu Grunde
liegen.
N u r a u f G r u n d e i n e r s t a t t g e f u n d e n e n o d e r
v e r m e i n t l i c h e n B e l e i d i g u n g s o l l e i n e
H e r a u s f o r d e r u n g , e i n D u e l l e r f o l g e n .
Die Beleidigungen können im Allgemeinen in zwei Gruppen
gefasst werden:
1. Directe Beleidigungen.
2. Indirecte Beleidigungen.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

PDF
The Rust Programming Language 2nd Edition Second Converted Steve Klabnik Caro...
PDF
The Rust Programming Language 2nd Edition Steve Klabnik
PDF
The Rust Programming Language 2nd Edition Steve Klabnik
PDF
The Rust Programming Language Steve Klabnik
PDF
(Ebook) The Rust Programming Language, Second Edition by Steve Klabnik, Carol...
PDF
The Rust Programming Language, Second Edition Steve Klabnik
PDF
Download Complete The Rust Programming Language 2nd Edition Steve Klabnik PDF...
PDF
The Rust Programming Language Steve Klabnik
The Rust Programming Language 2nd Edition Second Converted Steve Klabnik Caro...
The Rust Programming Language 2nd Edition Steve Klabnik
The Rust Programming Language 2nd Edition Steve Klabnik
The Rust Programming Language Steve Klabnik
(Ebook) The Rust Programming Language, Second Edition by Steve Klabnik, Carol...
The Rust Programming Language, Second Edition Steve Klabnik
Download Complete The Rust Programming Language 2nd Edition Steve Klabnik PDF...
The Rust Programming Language Steve Klabnik

Similar to The Rust Programming Language Second Edition 2 Converted Steve Klabnik (20)

PDF
Advanced Swift Updated For Swift 5 Chris Eidhof
PDF
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
PDF
7li7w devcon5
PDF
DEVCON1 - BooJs
PDF
Software Engineering Thailand: Programming with Scala
PDF
Eloquent JavaScript Book for Beginners to Learn Javascript
PDF
EloquenFundamentalsof Web Developmentt_JavaScript.pdf
PDF
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
PDF
(eBook PDF) Starting Out with C++: From Control Structures through Objects 8t...
PDF
(eBook PDF) Starting Out with C++: From Control Structures through Objects 8t...
PDF
(eBook PDF) Starting Out with C++: Early Objects 9th Edition
PDF
Who go Types in my Systems Programing!
PDF
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
PDF
(eBook PDF) Starting Out with C++: Early Objects 9th Edition
PDF
Luciano Ramalho - Fluent Python_ Clear, Concise, and Effective Programming-O'...
PDF
Core Java Volume I Fundamentals 12th Horstmann Cay
PDF
(eBook PDF) Starting Out with C++: From Control Structures through Objects, B...
PPTX
MozillaPH Rust Hack & Learn Session 2
PDF
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
PDF
(eBook PDF) Starting Out with C++: Early Objects 9th Edition
Advanced Swift Updated For Swift 5 Chris Eidhof
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
7li7w devcon5
DEVCON1 - BooJs
Software Engineering Thailand: Programming with Scala
Eloquent JavaScript Book for Beginners to Learn Javascript
EloquenFundamentalsof Web Developmentt_JavaScript.pdf
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
(eBook PDF) Starting Out with C++: From Control Structures through Objects 8t...
(eBook PDF) Starting Out with C++: From Control Structures through Objects 8t...
(eBook PDF) Starting Out with C++: Early Objects 9th Edition
Who go Types in my Systems Programing!
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
(eBook PDF) Starting Out with C++: Early Objects 9th Edition
Luciano Ramalho - Fluent Python_ Clear, Concise, and Effective Programming-O'...
Core Java Volume I Fundamentals 12th Horstmann Cay
(eBook PDF) Starting Out with C++: From Control Structures through Objects, B...
MozillaPH Rust Hack & Learn Session 2
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
(eBook PDF) Starting Out with C++: Early Objects 9th Edition
Ad

Recently uploaded (20)

PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Yogi Goddess Pres Conference Studio Updates
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PDF
Complications of Minimal Access Surgery at WLH
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
Lesson notes of climatology university.
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Trump Administration's workforce development strategy
PPTX
Cell Types and Its function , kingdom of life
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
GDM (1) (1).pptx small presentation for students
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Yogi Goddess Pres Conference Studio Updates
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
Complications of Minimal Access Surgery at WLH
Chinmaya Tiranga quiz Grand Finale.pdf
Lesson notes of climatology university.
Abdominal Access Techniques with Prof. Dr. R K Mishra
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
O7-L3 Supply Chain Operations - ICLT Program
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Trump Administration's workforce development strategy
Cell Types and Its function , kingdom of life
Module 4: Burden of Disease Tutorial Slides S2 2025
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Ad

The Rust Programming Language Second Edition 2 Converted Steve Klabnik

  • 1. The Rust Programming Language Second Edition 2 Converted Steve Klabnik download https://ebookbell.com/product/the-rust-programming-language- second-edition-2-converted-steve-klabnik-48000090 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. The Rust Programming Language 2nd Edition Second Converted Steve Klabnik Carol Nichols https://ebookbell.com/product/the-rust-programming-language-2nd- edition-second-converted-steve-klabnik-carol-nichols-49465120 The Rust Programming Language Covers Rust 2018 Illustrated Steve Klabnik https://ebookbell.com/product/the-rust-programming-language-covers- rust-2018-illustrated-steve-klabnik-50194554 The Rust Programming Language Steve Klabnik Carol Nichols https://ebookbell.com/product/the-rust-programming-language-steve- klabnik-carol-nichols-36194546 The Rust Programming Language Covers Rust 2018 Steve Klabnik Carol Nichols https://ebookbell.com/product/the-rust-programming-language-covers- rust-2018-steve-klabnik-carol-nichols-49850560
  • 3. The Rust Programming Language 1st Edition The Rust Project Developpers https://ebookbell.com/product/the-rust-programming-language-1st- edition-the-rust-project-developpers-23358024 The Rust Programming Language Steve Klabnik Carol Nichols https://ebookbell.com/product/the-rust-programming-language-steve- klabnik-carol-nichols-27553790 The Rust Programming Language Steve Klabnik Steve Carol Nichols https://ebookbell.com/product/the-rust-programming-language-steve- klabnik-steve-carol-nichols-36194548 The Rust Programming Language Covers Rust 2018 Carol Nichols https://ebookbell.com/product/the-rust-programming-language-covers- rust-2018-carol-nichols-37721398 The Rust Programming Language Steve Klabnik Carol Nichols https://ebookbell.com/product/the-rust-programming-language-steve- klabnik-carol-nichols-42174614
  • 6. CONTENTS IN DETAIL TITLE PAGE COPYRIGHT ABOUT THE AUTHORS FOREWORD PREFACE ACKNOWLEDGMENTS INTRODUCTION Who Rust Is For Teams of Developers Students Companies Open Source Developers People Who Value Speed and Stability Who This Book Is For How to Use This Book Resources and How to Contribute to This Book CHAPTER 1: GETTING STARTED Installation Installing rustup on Linux or macOS
  • 7. Installing rustup on Windows Troubleshooting Updating and Uninstalling Local Documentation Hello, World! Creating a Project Directory Writing and Running a Rust Program Anatomy of a Rust Program Compiling and Running Are Separate Steps Hello, Cargo! Creating a Project with Cargo Building and Running a Cargo Project Building for Release Cargo as Convention Summary CHAPTER 2: PROGRAMMING A GUESSING GAME Setting Up a New Project Processing a Guess Storing Values with Variables Receiving User Input Handling Potential Failure with Result Printing Values with println! Placeholders Testing the First Part Generating a Secret Number Using a Crate to Get More Functionality Generating a Random Number Comparing the Guess to the Secret Number Allowing Multiple Guesses with Looping Quitting After a Correct Guess
  • 8. Handling Invalid Input Summary CHAPTER 3: COMMON PROGRAMMING CONCEPTS Variables and Mutability Constants Shadowing Data Types Scalar Types Compound Types Functions Parameters Statements and Expressions Functions with Return Values Comments Control Flow if Expressions Repetition with Loops Summary CHAPTER 4: UNDERSTANDING OWNERSHIP What Is Ownership? Ownership Rules Variable Scope The String Type Memory and Allocation Ownership and Functions Return Values and Scope References and Borrowing Mutable References
  • 9. Dangling References The Rules of References The Slice Type String Slices Other Slices Summary CHAPTER 5: USING STRUCTS TO STRUCTURE RELATED DATA Defining and Instantiating Structs Using the Field Init Shorthand Creating Instances from Other Instances with Struct Update Syntax Using Tuple Structs Without Named Fields to Create D ifferent Types Unit-Like Structs Without Any Fields An Example Program Using Structs Refactoring with Tuples Refactoring with Structs: Adding More Meaning Adding Useful Functionality with Derived Traits Method Syntax Defining Methods Methods with More Parameters Associated Functions Multiple impl Blocks Summary CHAPTER 6: ENUMS AND PATTERN MATCHING Defining an Enum Enum Values The Option Enum and Its Advantages Over Null Values The match Control Flow Construct
  • 10. Patterns That Bind to Values Matching with Option<T> Matches Are Exhaustive Catch-All Patterns and the _ Placeholder Concise Control Flow with if let Summary CHAPTER 7: MANAGING GROWING PROJECTS WITH PACKAGES, CRAT ES, AND MODULES Packages and Crates Defining Modules to Control Scope and Privacy Paths for Referring to an Item in the Module Tree Exposing Paths with the pub Keyword Starting Relative Paths with super Making Structs and Enums Public Bringing Paths into Scope with the use Keyword Creating Idiomatic use Paths Providing New Names with the as Keyword Re-exporting Names with pub use Using External Packages Using Nested Paths to Clean Up Large use Lists The Glob Operator Separating Modules into Different Files Summary CHAPTER 8: COMMON COLLECTIONS Storing Lists of Values with Vectors Creating a New Vector Updating a Vector Reading Elements of Vectors
  • 11. Iterating Over the Values in a Vector Using an Enum to Store Multiple Types Dropping a Vector Drops Its Elements Storing UTF-8 Encoded Text with Strings What Is a String? Creating a New String Updating a String Indexing into Strings Slicing Strings Methods for Iterating Over Strings Strings Are Not So Simple Storing Keys with Associated Values in Hash Maps Creating a New Hash Map Accessing Values in a Hash Map Hash Maps and Ownership Updating a Hash Map Hashing Functions Summary CHAPTER 9: ERROR HANDLING Unrecoverable Errors with panic! Recoverable Errors with Result Matching on Different Errors Propagating Errors To panic! or Not to panic! Examples, Prototype Code, and Tests Cases in Which You Have More Information Than the Co mpiler Guidelines for Error Handling Creating Custom Types for Validation
  • 12. Summary CHAPTER 10: GENERIC TYPES, TRAITS, AND LIFETIMES Removing Duplication by Extracting a Function Generic Data Types In Function Definitions In Struct Definitions In Enum Definitions In Method Definitions Performance of Code Using Generics Traits: Defining Shared Behavior Defining a Trait Implementing a Trait on a Type Default Implementations Traits as Parameters Returning Types That Implement Traits Using Trait Bounds to Conditionally Implement Method s Validating References with Lifetimes Preventing Dangling References with Lifetimes The Borrow Checker Generic Lifetimes in Functions Lifetime Annotation Syntax Lifetime Annotations in Function Signatures Thinking in Terms of Lifetimes Lifetime Annotations in Struct Definitions Lifetime Elision Lifetime Annotations in Method Definitions The Static Lifetime
  • 13. Generic Type Parameters, Trait Bounds, and Lifetimes To gether Summary CHAPTER 11: WRITING AUTOMATED TESTS How to Write Tests The Anatomy of a Test Function Checking Results with the assert! Macro Testing Equality with the assert_eq! and assert_ne! Macros Adding Custom Failure Messages Checking for Panics with should_panic Using Result<T, E> in Tests Controlling How Tests Are Run Running Tests in Parallel or Consecutively Showing Function Output Running a Subset of Tests by Name Ignoring Some Tests Unless Specifically Requested Test Organization Unit Tests Integration Tests Summary CHAPTER 12: AN I/O PROJECT: BUILDING A COMMAND LINE PROG RAM Accepting Command Line Arguments Reading the Argument Values Saving the Argument Values in Variables Reading a File Refactoring to Improve Modularity and Error Handling Separation of Concerns for Binary Projects
  • 14. Fixing the Error Handling Extracting Logic from main Splitting Code into a Library Crate Developing the Library’s Functionality with Test-Drive n Development Writing a Failing Test Writing Code to Pass the Test Working with Environment Variables Writing a Failing Test for the Case-Insensitive Sear ch Function Implementing the search_case_insensitive Function Writing Error Messages to Standard Error Instead of Sta ndard Output Checking Where Errors Are Written Printing Errors to Standard Error Summary CHAPTER 13: FUNCTIONAL LANGUAGE FEATURES: ITERATORS AND CLOSURES Closures: Anonymous Functions That Capture Their Enviro nment Capturing the Environment with Closures Closure Type Inference and Annotation Capturing References or Moving Ownership Moving Captured Values Out of Closures and the Fn Tr aits Processing a Series of Items with Iterators The Iterator Trait and the next Method Methods That Consume the Iterator Methods That Produce Other Iterators Using Closures That Capture Their Environment
  • 15. Improving Our I/O Project Removing a clone Using an Iterator Making Code Clearer with Iterator Adapters Choosing Between Loops and Iterators Comparing Performance: Loops vs. Iterators Summary CHAPTER 14: MORE ABOUT CARGO AND CRATES.IO Customizing Builds with Release Profiles Publishing a Crate to Crates.io Making Useful Documentation Comments Exporting a Convenient Public API with pub use Setting Up a Crates.io Account Adding Metadata to a New Crate Publishing to Crates.io Publishing a New Version of an Existing Crate Deprecating Versions from Crates.io with cargo yank Cargo Workspaces Creating a Workspace Creating the Second Package in the Workspace Installing Binaries with cargo install Extending Cargo with Custom Commands Summary CHAPTER 15: SMART POINTERS Using Box<T> to Point to Data on the Heap Using Box<T> to Store Data on the Heap Enabling Recursive Types with Boxes Treating Smart Pointers Like Regular References with De ref
  • 16. Following the Pointer to the Value Using Box<T> Like a Reference Defining Our Own Smart Pointer Implementing the Deref Trait Implicit Deref Coercions with Functions and Methods How Deref Coercion Interacts with Mutability Running Code on Cleanup with the Drop Trait Rc<T>, the Reference Counted Smart Pointer Using Rc<T> to Share Data Cloning an Rc<T> Increases the Reference Count RefCell<T> and the Interior Mutability Pattern Enforcing Borrowing Rules at Runtime with RefCell<T> Interior Mutability: A Mutable Borrow to an Immutabl e Value Allowing Multiple Owners of Mutable Data with Rc<T> and RefCell<T> Reference Cycles Can Leak Memory Creating a Reference Cycle Preventing Reference Cycles Using Weak<T> Summary CHAPTER 16: FEARLESS CONCURRENCY Using Threads to Run Code Simultaneously Creating a New Thread with spawn Waiting for All Threads to Finish Using join Handles Using move Closures with Threads Using Message Passing to Transfer Data Between Threads Channels and Ownership Transference Sending Multiple Values and Seeing the Receiver Wait ing
  • 17. Creating Multiple Producers by Cloning the Transmitt er Shared-State Concurrency Using Mutexes to Allow Access to Data from One Threa d at a Time Similarities Between RefCell<T>/Rc<T> and Mutex<T>/A rc<T> Extensible Concurrency with the Send and Sync Traits Allowing Transference of Ownership Between Threads w ith Send Allowing Access from Multiple Threads with Sync Implementing Send and Sync Manually Is Unsafe Summary CHAPTER 17: OBJECT-ORIENTED PROGRAMMING FEATURES Characteristics of Object-Oriented Languages Objects Contain Data and Behavior Encapsulation That Hides Implementation Details Inheritance as a Type System and as Code Sharing Using Trait Objects That Allow for Values of Different Types Defining a Trait for Common Behavior Implementing the Trait Trait Objects Perform Dynamic Dispatch Implementing an Object-Oriented Design Pattern Defining Post and Creating a New Instance in the Dra ft State Storing the Text of the Post Content Ensuring the Content of a Draft Post Is Empty Requesting a Review Changes the Post’s State Adding approve to Change the Behavior of content
  • 18. Trade-offs of the State Pattern Summary CHAPTER 18: PATTERNS AND MATCHING All the Places Patterns Can Be Used match Arms Conditional if let Expressions while let Conditional Loops for Loops let Statements Function Parameters Refutability: Whether a Pattern Might Fail to Match Pattern Syntax Matching Literals Matching Named Variables Multiple Patterns Matching Ranges of Values with ..= Destructuring to Break Apart Values Ignoring Values in a Pattern Extra Conditionals with Match Guards @ Bindings Summary CHAPTER 19: ADVANCED FEATURES Unsafe Rust Unsafe Superpowers Dereferencing a Raw Pointer Calling an Unsafe Function or Method Accessing or Modifying a Mutable Static Variable Implementing an Unsafe Trait
  • 19. Accessing Fields of a Union When to Use Unsafe Code Advanced Traits Associated Types Default Generic Type Parameters and Operator Overloa ding Disambiguating Between Methods with the Same Name Using Supertraits Using the Newtype Pattern to Implement External Trai ts Advanced Types Using the Newtype Pattern for Type Safety and Abstra ction Creating Type Synonyms with Type Aliases The Never Type That Never Returns Dynamically Sized Types and the Sized Trait Advanced Functions and Closures Function Pointers Returning Closures Macros The Difference Between Macros and Functions Declarative Macros with macro_rules! for General Met aprogramming Procedural Macros for Generating Code from Attribute s How to Write a Custom derive Macro Attribute-Like Macros Function-Like Macros Summary
  • 20. CHAPTER 20: FINAL PROJECT: BUILDING A MULTITHREADED WEB SERVER Building a Single-Threaded Web Server Listening to the TCP Connection Reading the Request A Closer Look at an HTTP Request Writing a Response Returning Real HTML Validating the Request and Selectively Responding A Touch of Refactoring Turning Our Single-Threaded Server into a Multithreaded Server Simulating a Slow Request Improving Throughput with a Thread Pool Graceful Shutdown and Cleanup Implementing the Drop Trait on ThreadPool Signaling to the Threads to Stop Listening for Jobs Summary APPENDIX A: KEYWORDS Keywords Currently in Use Keywords Reserved for Future Use Raw Identifiers APPENDIX B: OPERATORS AND SYMBOLS Operators Non-operator Symbols APPENDIX C: DERIVABLE TRAITS Debug for Programmer Output PartialEq and Eq for Equality Comparisons
  • 21. PartialOrd and Ord for Ordering Comparisons Clone and Copy for Duplicating Values Hash for Mapping a Value to a Value of Fixed Size Default for Default Values APPENDIX D: USEFUL DEVELOPMENT TOOLS Automatic Formatting with rustfmt Fix Your Code with rustfix More Lints with Clippy IDE Integration Using rust-analyzer APPENDIX E: EDITIONS INDEX
  • 22. THE RUST PROGRAMMING LANGUAGE 2nd Edition by Steve Klabnik and Carol Nichols, with contributions from the Rust Community
  • 23. THE RUST PROGRAMMING LANGUAGE, 2ND EDITION. Copyright © 2023 by the Rust Foundation and the Rust Project Developers. All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. Printed in the United States of America First printing 27 26 25 24 23 1 2 3 4 5 ISBN-13: 978-1-7185-0310-6 (print) ISBN-13: 978-1-7185-0311-3 (ebook) Publisher: William Pollock Managing Editor: Jill Franklin Production Manager: Sabrina Plomitallo-González Production Editors: Jennifer Kepler and Katrina Horlbeck Olsen Developmental Editor: Liz Chadwick Cover Illustration: Karen Rustad Tölva Interior Design: Octopod Studios Technical Reviewer: JT Copyeditor: Audrey Doyle Compositor: Jeff Lytle, Happenstance Type-O-Rama Proofreader: Liz Wheeler For information on distribution, bulk sales, corporate sales, or translations, please contact No Starch Press, Inc. directly at [email protected] or: No Starch Press, Inc. 245 8th Street, San Francisco, CA 94103 phone: 1.415.863.9900 www.nostarch.com The Library of Congress has catalogued the first edition as follows: Names: Klabnik, Steve, author. | Nichols, Carol, 1983- eauthor. Title: The Rust programming language / by Steve Klabnik and Carol Nichols ; with contributions from the Rust Community. Description: San Francisco : No Starch Press, Inc., 2018. | Includes index. Identifiers: LCCN 2018014097 (print) | LCCN 2018019844 (ebook) | ISBN 9781593278519 (epub) | ISBN 1593278519 (epub) | ISBN 9781593278281 (paperback) | ISBN 1593278284 (paperback) Subjects: LCSH: Rust (Computer programming language) | BISAC: COMPUTERS / Programming / Open Source. | COMPUTERS / Programming Languages / General. | COMPUTERS / Programming / General. Classification: LCC QA76.73.R87 (ebook) | LCC QA76.73.R87 K53 2018 (print) | DDC
  • 24. 005.13/3--dc23 LC record available at https://lccn.loc.gov/2018014097 No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of this work, neither the authors nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it.
  • 25. About the Authors Steve Klabnik was the lead for the Rust documentation team and was one of Rust’s core developers. A frequent speaker and a prolific open source contributor, he previously worked on projects such as Ruby and Ruby on Rails. Carol Nichols is a member of the Rust Crates.io Team and a former member of the Rust Core Team. She’s a co-founder of Integer 32, LLC, the world’s first Rust-focused software consultancy. Nichols has also organized the Rust Belt Rust Conference. About the Technical Reviewer JT is a Rust core team member and the co-creator of the Rust error message format, Rust Language Server (RLS), and Nushell. They first started using Rust in 2011, and in 2016 joined Mozilla to work on Rust full-time, helping to shape its direction for widespread use. These days, they are a freelance Rust trainer and advocate for safe systems programming.
  • 26. FOREWORD It wasn’t always so clear, but the Rust programming language is fundamentally about empowerment: no matter what kind of code you are writing now, Rust empowers you to reach further, to program with confidence in a wider variety of domains than you did before. Take, for example, “systems-level” work that deals with low-level details of memory management, data representation, and concurrency. Traditionally, this realm of programming is seen as arcane, accessible to only a select few who have devoted the necessary years to learning it to avoid its infamous pitfalls. And even those who practice it do so with caution, lest their code be open to exploits, crashes, or corruption. Rust breaks down these barriers by eliminating the old pitfalls and providing a friendly, polished set of tools to help you along the way. Programmers who need to “dip down” into lower-level control can do so with Rust, without taking on the customary risk of crashes or security holes and without having to learn the fine points of a fickle toolchain. Better yet, the language is designed to guide you naturally toward reliable code that is efficient in terms of speed and memory usage. Programmers who are already working with low-level code can use Rust to raise their ambitions. For example, introducing parallelism in Rust is a relatively low-risk operation: the compiler will catch the classical mistakes for you. And you can tackle more aggressive optimizations in your code with the confidence that you won’t accidentally introduce crashes or vulnerabilities. But Rust isn’t limited to low-level systems programming. It’s expressive and ergonomic enough to make CLI apps, web servers,
  • 27. and many other kinds of code quite pleasant to write—you’ll find simple examples later in the book. Working with Rust allows you to build skills that transfer from one domain to another; you can learn Rust by writing a web app, then apply those same skills to target your Raspberry Pi. This book fully embraces the potential of Rust to empower its users. It’s a friendly and approachable text intended to help you level up not just your knowledge of Rust, but also your reach and confidence as a programmer in general. So dive in, get ready to learn —and welcome to the Rust community! Nicholas Matsakis and Aaron Turon
  • 28. PREFACE This version of the text assumes you’re using Rust 1.62.0 (released 2022-06-30) or later with edition="2021" in the Cargo.toml file of all projects to configure them to use Rust 2021 edition idioms. See “Installation” on page 1 for instructions on installing or updating Rust, and see Appendix E for information on editions. The 2021 edition of the Rust language includes a number of improvements that make Rust more ergonomic and that correct some inconsistencies. On top of a general update to reflect these improvements, this rendition of the book has a number of improvements to address specific feedback: Chapter 7 contains a new quick reference section on organizing your code into multiple files with modules. Chapter 13 has new and improved closure examples that more clearly illustrate captures, the move keyword, and the Fn traits. We fixed a number of small errors and imprecise wording throughout the book. Thank you to the readers who reported them! Note that any code from earlier renditions of this book that compiled will continue to compile with the relevant edition in the project’s Cargo.toml, even as you update the Rust compiler version you’re using. That’s Rust’s backward-compatibility guarantees at work!
  • 29. ACKNOWLEDGMENTS We would like to thank everyone who has worked on the Rust language for creating an amazing language worth writing a book about. We’re grateful to everyone in the Rust community for being welcoming and creating an environment worth welcoming more folks into. We’re especially thankful for everyone who read early versions of this book online and provided feedback, bug reports, and pull requests. Special thanks to Eduard-Mihai Burtescu, Alex Crichton, and JT for providing technical review, and to Karen Rustad Tölva for the cover art. Thank you to our team at No Starch, including Bill Pollock, Liz Chadwick, and Janelle Ludowise, for improving this book and bringing it to print. Carol is grateful for the opportunity to work on this book. She thanks her family for their constant love and support, especially her husband, Jake Goulding, and her daughter, Vivian.
  • 30. INTRODUCTION Welcome to The Rust Programming Language, an introductory book about Rust. The Rust programming language helps you write faster, more reliable software. High-level ergonomics and low-level control are often at odds in programming language design; Rust challenges that conflict. Through balancing powerful technical capacity and a great developer experience, Rust gives you the option to control low-level details (such as memory usage) without all the hassle traditionally associated with such control. Who Rust Is For Rust is ideal for many people for a variety of reasons. Let’s look at a few of the most important groups. Teams of Developers Rust is proving to be a productive tool for collaborating among large teams of developers with varying levels of systems programming knowledge. Low-level code is prone to various subtle bugs, which in most other languages can only be caught through extensive testing and careful code review by experienced developers. In Rust, the
  • 31. compiler plays a gatekeeper role by refusing to compile code with these elusive bugs, including concurrency bugs. By working alongside the compiler, the team can spend their time focusing on the program’s logic rather than chasing down bugs. Rust also brings contemporary developer tools to the systems programming world: Cargo, the included dependency manager and build tool, makes adding, compiling, and managing dependencies painless and consistent across the Rust ecosystem. The rustfmt formatting tool ensures a consistent coding style across developers. The Rust Language Server powers integrated development environment (IDE) integration for code completion and inline error messages. By using these and other tools in the Rust ecosystem, developers can be productive while writing systems-level code. Students Rust is for students and those who are interested in learning about systems concepts. Using Rust, many people have learned about topics like operating systems development. The community is very welcoming and happy to answer students’ questions. Through efforts such as this book, the Rust teams want to make systems concepts more accessible to more people, especially those new to programming. Companies Hundreds of companies, large and small, use Rust in production for a variety of tasks, including command line tools, web services, DevOps tooling, embedded devices, audio and video analysis and transcoding, cryptocurrencies, bioinformatics, search engines, Internet of Things applications, machine learning, and even major parts of the Firefox web browser.
  • 32. Open Source Developers Rust is for people who want to build the Rust programming language, community, developer tools, and libraries. We’d love to have you contribute to the Rust language. People Who Value Speed and Stability Rust is for people who crave speed and stability in a language. By speed, we mean both how quickly Rust code can run and the speed at which Rust lets you write programs. The Rust compiler’s checks ensure stability through feature additions and refactoring. This is in contrast to the brittle legacy code in languages without these checks, which developers are often afraid to modify. By striving for zero-cost abstractions—higher-level features that compile to lower-level code as fast as code written manually—Rust endeavors to make safe code be fast code as well. The Rust language hopes to support many other users as well; those mentioned here are merely some of the biggest stakeholders. Overall, Rust’s greatest ambition is to eliminate the trade-offs that programmers have accepted for decades by providing safety and productivity, speed and ergonomics. Give Rust a try and see if its choices work for you.
  • 33. Who This Book Is For This book assumes that you’ve written code in another programming language, but doesn’t make any assumptions about which one. We’ve tried to make the material broadly accessible to those from a wide variety of programming backgrounds. We don’t spend a lot of time talking about what programming is or how to think about it. If you’re entirely new to programming, you would be better served by reading a book that specifically provides an introduction to programming. How to Use This Book In general, this book assumes that you’re reading it in sequence from front to back. Later chapters build on concepts in earlier chapters, and earlier chapters might not delve into details on a particular topic but will revisit the topic in a later chapter. You’ll find two kinds of chapters in this book: concept chapters and project chapters. In concept chapters, you’ll learn about an aspect of Rust. In project chapters, we’ll build small programs together, applying what you’ve learned so far. Chapter 2, Chapter 12, and Chapter 20 are project chapters; the rest are concept chapters. Chapter 1 explains how to install Rust, how to write a “Hello, world!” program, and how to use Cargo, Rust’s package manager and build tool. Chapter 2 is a hands-on introduction to writing a program in Rust, having you build up a number-guessing game. Here, we cover concepts at a high level, and later chapters will provide additional detail. If you want to get your hands dirty right away, Chapter 2 is the place for that. Chapter 3 covers Rust features that are similar to those of other programming languages, and in Chapter 4 you’ll learn about Rust’s ownership system. If you’re a particularly meticulous learner who prefers to learn every detail before moving on to the next, you might want to skip Chapter 2 and go straight to Chapter 3, returning to Chapter 2 when you’d like to work on a project applying the details you’ve learned.
  • 34. Chapter 5 discusses structs and methods, and Chapter 6 covers enums, match expressions, and the if let control flow construct. You’ll use structs and enums to make custom types in Rust. In Chapter 7, you’ll learn about Rust’s module system and about privacy rules for organizing your code and its public application programming interface (API). Chapter 8 discusses some common collection data structures that the standard library provides, such as vectors, strings, and hash maps. Chapter 9 explores Rust’s error- handling philosophy and techniques. Chapter 10 digs into generics, traits, and lifetimes, which give you the power to define code that applies to multiple types. Chapter 11 is all about testing, which even with Rust’s safety guarantees is necessary to ensure your program’s logic is correct. In Chapter 12, we’ll build our own implementation of a subset of functionality from the grep command line tool that searches for text within files. For this, we’ll use many of the concepts we discussed in the previous chapters. Chapter 13 explores closures and iterators: features of Rust that come from functional programming languages. In Chapter 14, we’ll examine Cargo in more depth and talk about best practices for sharing your libraries with others. Chapter 15 discusses smart pointers that the standard library provides and the traits that enable their functionality. In Chapter 16, we’ll walk through different models of concurrent programming and talk about how Rust helps you program in multiple threads fearlessly. Chapter 17 looks at how Rust idioms compare to object-oriented programming principles you might be familiar with. Chapter 18 is a reference on patterns and pattern matching, which are powerful ways of expressing ideas throughout Rust programs. Chapter 19 contains a smorgasbord of advanced topics of interest, including unsafe Rust, macros, and more about lifetimes, traits, types, functions, and closures. In Chapter 20, we’ll complete a project in which we’ll implement a low-level multithreaded web server!
  • 35. Finally, some appendixes contain useful information about the language in a more reference-like format. Appendix A covers Rust’s keywords, Appendix B covers Rust’s operators and symbols, Appendix C covers derivable traits provided by the standard library, Appendix D covers some useful development tools, and Appendix E explains Rust editions. There is no wrong way to read this book: if you want to skip ahead, go for it! You might have to jump back to earlier chapters if you experience any confusion. But do whatever works for you. An important part of the process of learning Rust is learning how to read the error messages the compiler displays: these will guide you toward working code. As such, we’ll provide many examples that don’t compile along with the error message the compiler will show you in each situation. Know that if you enter and run a random example, it may not compile! Make sure you read the surrounding text to see whether the example you’re trying to run is meant to error. In most situations, we’ll lead you to the correct version of any code that doesn’t compile. Resources and How to Contribute to This Book This book is open source. If you find an error, please don’t hesitate to file an issue or send a pull request on GitHub at https://github.com/ rust-lang/book. Please see CONTRIBUTING.md at https://github.c om/rust-lang/book/blob/main/CONTRIBUTING.md for more details. The source code for the examples in this book, errata, and other information are available at https://nostarch.com/rust-programmi ng-language-2nd-edition.
  • 36. 1 GETTING STARTED Let’s start your Rust journey! There’s a lot to learn, but every journey starts somewhere. In this chapter, we’ll discuss: Installing Rust on Linux, macOS, and Windows Writing a program that prints Hello, world! Using cargo, Rust’s package manager and build system Installation The first step is to install Rust. We’ll download Rust through rustup, a command line tool for managing Rust versions and associated tools. You’ll need an internet connection for the download. NOTE If you prefer not to use rustup for some reason, please see the Other Rust Installation Methods page at https://forge.rust-l ang.org/infra/other-installation-methods.html for more options. The following steps install the latest stable version of the Rust compiler. Rust’s stability guarantees ensure that all the examples in the book that compile will continue to compile with newer Rust versions. The output might differ slightly between versions because
  • 37. Rust often improves error messages and warnings. In other words, any newer, stable version of Rust you install using these steps should work as expected with the content of this book. COMMAND LINE NOTATION In this chapter and throughout the book, we’ll show some commands used in the terminal. Lines that you should enter in a terminal all start with $. You don’t need to type the $ character; it’s the command line prompt shown to indicate the start of each command. Lines that don’t start with $ typically show the output of the previous command. Additionally, PowerShell-specific examples will use > rather than $. Installing rustup on Linux or macOS If you’re using Linux or macOS, open a terminal and enter the following command: $ curl --proto '=https' --tlsv1.3 https://sh.rustup.rs -sSf | sh The command downloads a script and starts the installation of the rustup tool, which installs the latest stable version of Rust. You might be prompted for your password. If the install is successful, the following line will appear: Rust is installed now. Great! You will also need a linker, which is a program that Rust uses to join its compiled outputs into one file. It is likely you already have one. If you get linker errors, you should install a C compiler, which will typically include a linker. A C compiler is also useful because some common Rust packages depend on C code and will need a C compiler. On macOS, you can get a C compiler by running: $ xcode-select --install
  • 38. Linux users should generally install GCC or Clang, according to their distribution’s documentation. For example, if you use Ubuntu, you can install the build-essential package. Installing rustup on Windows On Windows, go to https://www.rust-lang.org/tools/install and follow the instructions for installing Rust. At some point in the installation, you’ll receive a message explaining that you’ll also need the MSVC build tools for Visual Studio 2013 or later. To acquire the build tools, you’ll need to install Visual Studio 2022 from https://visualstudio.microsoft.com/downloads. When asked which workloads to install, include: “Desktop Development with C++” The Windows 10 or 11 SDK The English language pack component, along with any other language pack of your choosing The rest of this book uses commands that work in both cmd.exe and PowerShell. If there are specific differences, we’ll explain which to use. Troubleshooting To check whether you have Rust installed correctly, open a shell and enter this line: $ rustc --version You should see the version number, commit hash, and commit date for the latest stable version that has been released, in the following format: rustc x.y.z (abcabcabc yyyy-mm-dd)
  • 39. If you see this information, you have installed Rust successfully! If you don’t see this information, check that Rust is in your %PATH% system variable as follows. In Windows CMD, use: > echo %PATH% In PowerShell, use: > echo $env:Path In Linux and macOS, use: $ echo $PATH If that’s all correct and Rust still isn’t working, there are a number of places you can get help. Find out how to get in touch with other Rustaceans (a silly nickname we call ourselves) on the community page at https://www.rust-lang.org/community. Updating and Uninstalling Once Rust is installed via rustup, updating to a newly released version is easy. From your shell, run the following update script: $ rustup update To uninstall Rust and rustup, run the following uninstall script from your shell: $ rustup self uninstall Local Documentation The installation of Rust also includes a local copy of the documentation so that you can read it offline. Run rustup doc to open the local documentation in your browser.
  • 40. Any time a type or function is provided by the standard library and you’re not sure what it does or how to use it, use the application programming interface (API) documentation to find out! Hello, World! Now that you’ve installed Rust, it’s time to write your first Rust program. It’s traditional when learning a new language to write a little program that prints the text Hello, world! to the screen, so we’ll do the same here! NOTE This book assumes basic familiarity with the command line. Rust makes no specific demands about your editing or tooling or where your code lives, so if you prefer to use an integrated development environment (IDE) instead of the command line, feel free to use your favorite IDE. Many IDEs now have some degree of Rust support; check the IDE’s documentation for details. The Rust team has been focusing on enabling great IDE support via rust-analyzer. See Appendix D for more details. Creating a Project Directory You’ll start by making a directory to store your Rust code. It doesn’t matter to Rust where your code lives, but for the exercises and projects in this book, we suggest making a projects directory in your home directory and keeping all your projects there. Open a terminal and enter the following commands to make a projects directory and a directory for the “Hello, world!” project within the projects directory. For Linux, macOS, and PowerShell on Windows, enter this: $ mkdir ~/projects $ cd ~/projects $ mkdir hello_world $ cd hello_world
  • 41. For Windows CMD, enter this: > mkdir "%USERPROFILE%projects" > cd /d "%USERPROFILE%projects" > mkdir hello_world > cd hello_world Writing and Running a Rust Program Next, make a new source file and call it main.rs. Rust files always end with the .rs extension. If you’re using more than one word in your filename, the convention is to use an underscore to separate them. For example, use hello_world.rs rather than helloworld.rs. Now open the main.rs file you just created and enter the code in Li sting 1-1. main.rs fn main() { println!("Hello, world!"); } Listing 1-1: A program that prints Hello, world! Save the file and go back to your terminal window in the ~/projects/hello_world directory. On Linux or macOS, enter the following commands to compile and run the file: $ rustc main.rs $ ./main Hello, world! On Windows, enter the command .main.exe instead of ./main: > rustc main.rs > .main.exe Hello, world! Regardless of your operating system, the string Hello, world! should print to the terminal. If you don’t see this output, refer back to
  • 42. “Troubleshooting” on page 3 for ways to get help. If Hello, world! did print, congratulations! You’ve officially written a Rust program. That makes you a Rust programmer—welcome! Anatomy of a Rust Program Let’s review this “Hello, world!” program in detail. Here’s the first piece of the puzzle: fn main() { } These lines define a function named main. The main function is special: it is always the first code that runs in every executable Rust program. Here, the first line declares a function named main that has no parameters and returns nothing. If there were parameters, they would go inside the parentheses (). The function body is wrapped in {}. Rust requires curly brackets around all function bodies. It’s good style to place the opening curly bracket on the same line as the function declaration, adding one space in between. NOTE If you want to stick to a standard style across Rust projects, you can use an automatic formatter tool called rustfmt to format your code in a particular style (more on rustfmt in Appendix D). The Rust team has included this tool with the standard Rust distribution, as rustc is, so it should already be installed on your computer! The body of the main function holds the following code: println!("Hello, world!"); This line does all the work in this little program: it prints text to the screen. There are four important details to notice here. First, Rust style is to indent with four spaces, not a tab.
  • 43. Second, println! calls a Rust macro. If it had called a function instead, it would be entered as println (without the !). We’ll discuss Rust macros in more detail in Chapter 19. For now, you just need to know that using a ! means that you’re calling a macro instead of a normal function and that macros don’t always follow the same rules as functions. Third, you see the "Hello, world!" string. We pass this string as an argument to println!, and the string is printed to the screen. Fourth, we end the line with a semicolon (;), which indicates that this expression is over and the next one is ready to begin. Most lines of Rust code end with a semicolon. Compiling and Running Are Separate Steps You’ve just run a newly created program, so let’s examine each step in the process. Before running a Rust program, you must compile it using the Rust compiler by entering the rustc command and passing it the name of your source file, like this: $ rustc main.rs If you have a C or C++ background, you’ll notice that this is similar to gcc or clang. After compiling successfully, Rust outputs a binary executable. On Linux, macOS, and PowerShell on Windows, you can see the executable by entering the ls command in your shell: $ ls main main.rs On Linux and macOS, you’ll see two files. With PowerShell on Windows, you’ll see the same three files that you would see using CMD. With CMD on Windows, you would enter the following: > dir /B %= the /B option says to only show the file names =% main.exe
  • 44. main.pdb main.rs This shows the source code file with the .rs extension, the executable file (main.exe on Windows, but main on all other platforms), and, when using Windows, a file containing debugging information with the .pdb extension. From here, you run the main or main.exe file, like this: $ ./main # or .main.exe on Windows If your main.rs is your “Hello, world!” program, this line prints Hello, world! to your terminal. If you’re more familiar with a dynamic language, such as Ruby, Python, or JavaScript, you might not be used to compiling and running a program as separate steps. Rust is an ahead-of-time compiled language, meaning you can compile a program and give the executable to someone else, and they can run it even without having Rust installed. If you give someone a .rb, .py, or .js file, they need to have a Ruby, Python, or JavaScript implementation installed (respectively). But in those languages, you only need one command to compile and run your program. Everything is a trade-off in language design. Just compiling with rustc is fine for simple programs, but as your project grows, you’ll want to manage all the options and make it easy to share your code. Next, we’ll introduce you to the Cargo tool, which will help you write real-world Rust programs. Hello, Cargo! Cargo is Rust’s build system and package manager. Most Rustaceans use this tool to manage their Rust projects because Cargo handles a lot of tasks for you, such as building your code, downloading the libraries your code depends on, and building those libraries. (We call the libraries that your code needs dependencies.) The simplest Rust programs, like the one we’ve written so far, don’t have any dependencies. If we had built the “Hello, world!”
  • 45. project with Cargo, it would only use the part of Cargo that handles building your code. As you write more complex Rust programs, you’ll add dependencies, and if you start a project using Cargo, adding dependencies will be much easier to do. Because the vast majority of Rust projects use Cargo, the rest of this book assumes that you’re using Cargo too. Cargo comes installed with Rust if you used the official installers discussed in “Installation” on page 1. If you installed Rust through some other means, check whether Cargo is installed by entering the following in your terminal: $ cargo --version If you see a version number, you have it! If you see an error, such as command not found, look at the documentation for your method of installation to determine how to install Cargo separately. Creating a Project with Cargo Let’s create a new project using Cargo and look at how it differs from our original “Hello, world!” project. Navigate back to your projects directory (or wherever you decided to store your code). Then, on any operating system, run the following: $ cargo new hello_cargo $ cd hello_cargo The first command creates a new directory and project called hello_cargo. We’ve named our project hello_cargo, and Cargo creates its files in a directory of the same name. Go into the hello_cargo directory and list the files. You’ll see that Cargo has generated two files and one directory for us: a Cargo.toml file and a src directory with a main.rs file inside. It has also initialized a new Git repository along with a .gitignore file. Git files won’t be generated if you run cargo new within an existing Git repository; you can override this behavior by using cargo new -- vcs=git.
  • 46. NOTE Git is a common version control system. You can change cargo new to use a different version control system or no version control system by using the --vcs flag. Run cargo new --help to see the available options. Open Cargo.toml in your text editor of choice. It should look similar to the code in Listing 1-2. Cargo.toml [package] name = "hello_cargo" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/carg o/reference/manifest.html [dependencies] Listing 1-2: Contents of Cargo.toml generated by cargo new This file is in the TOML (Tom’s Obvious, Minimal Language) format, which is Cargo’s configuration format. The first line, [package], is a section heading that indicates that the following statements are configuring a package. As we add more information to this file, we’ll add other sections. The next three lines set the configuration information Cargo needs to compile your program: the name, the version, and the edition of Rust to use. We’ll talk about the edition key in Appendix E. The last line, [dependencies], is the start of a section for you to list any of your project’s dependencies. In Rust, packages of code are referred to as crates. We won’t need any other crates for this project, but we will in the first project in Chapter 2, so we’ll use this dependencies section then. Now open src/main.rs and take a look: src/main.rs
  • 47. fn main() { println!("Hello, world!"); } Cargo has generated a “Hello, world!” program for you, just like the one we wrote in Listing 1-1! So far, the differences between our project and the project Cargo generated are that Cargo placed the code in the src directory and we have a Cargo.toml configuration file in the top directory. Cargo expects your source files to live inside the src directory. The top-level project directory is just for README files, license information, configuration files, and anything else not related to your code. Using Cargo helps you organize your projects. There’s a place for everything, and everything is in its place. If you started a project that doesn’t use Cargo, as we did with the “Hello, world!” project, you can convert it to a project that does use Cargo. Move the project code into the src directory and create an appropriate Cargo.toml file. Building and Running a Cargo Project Now let’s look at what’s different when we build and run the “Hello, world!” program with Cargo! From your hello_cargo directory, build your project by entering the following command: $ cargo build Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo) Finished dev [unoptimized + debuginfo] target(s) in 2.85 secs This command creates an executable file in target/debug/hello_cargo (or targetdebughello_cargo.exe on Windows) rather than in your current directory. Because the default build is a debug build, Cargo puts the binary in a directory named debug. You can run the executable with this command: $ ./target/debug/hello_cargo # or .targetdebughello_cargo.exe on Wind ows Hello, world!
  • 48. If all goes well, Hello, world! should print to the terminal. Running cargo build for the first time also causes Cargo to create a new file at the top level: Cargo.lock. This file keeps track of the exact versions of dependencies in your project. This project doesn’t have dependencies, so the file is a bit sparse. You won’t ever need to change this file manually; Cargo manages its contents for you. We just built a project with cargo build and ran it with ./target/debug/hello_cargo, but we can also use cargo run to compile the code and then run the resultant executable all in one command: $ cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs Running `target/debug/hello_cargo` Hello, world! Using cargo run is more convenient than having to remember to run cargo build and then use the whole path to the binary, so most developers use cargo run. Notice that this time we didn’t see output indicating that Cargo was compiling hello_cargo. Cargo figured out that the files hadn’t changed, so it didn’t rebuild but just ran the binary. If you had modified your source code, Cargo would have rebuilt the project before running it, and you would have seen this output: $ cargo run Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo) Finished dev [unoptimized + debuginfo] target(s) in 0.33 secs Running `target/debug/hello_cargo` Hello, world! Cargo also provides a command called cargo check. This command quickly checks your code to make sure it compiles but doesn’t produce an executable: $ cargo check Checking hello_cargo v0.1.0 (file:///projects/hello_cargo) Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs
  • 49. Why would you not want an executable? Often, cargo check is much faster than cargo build because it skips the step of producing an executable. If you’re continually checking your work while writing the code, using cargo check will speed up the process of letting you know if your project is still compiling! As such, many Rustaceans run cargo check periodically as they write their program to make sure it compiles. Then they run cargo build when they’re ready to use the executable. Let’s recap what we’ve learned so far about Cargo: We can create a project using cargo new. We can build a project using cargo build. We can build and run a project in one step using cargo run. We can build a project without producing a binary to check for errors using cargo check. Instead of saving the result of the build in the same directory as our code, Cargo stores it in the target/debug directory. An additional advantage of using Cargo is that the commands are the same no matter which operating system you’re working on. So, at this point, we’ll no longer provide specific instructions for Linux and macOS versus Windows. Building for Release When your project is finally ready for release, you can use cargo build --release to compile it with optimizations. This command will create an executable in target/release instead of target/debug. The optimizations make your Rust code run faster, but turning them on lengthens the time it takes for your program to compile. This is why there are two different profiles: one for development, when you want to rebuild quickly and often, and another for building the final program you’ll give to a user that won’t be rebuilt repeatedly and that will run as fast as possible. If you’re benchmarking your code’s running time, be sure to run cargo build --release and benchmark with the executable in target/release.
  • 50. Cargo as Convention With simple projects, Cargo doesn’t provide a lot of value over just using rustc, but it will prove its worth as your programs become more intricate. Once programs grow to multiple files or need a dependency, it’s much easier to let Cargo coordinate the build. Even though the hello_cargo project is simple, it now uses much of the real tooling you’ll use in the rest of your Rust career. In fact, to work on any existing projects, you can use the following commands to check out the code using Git, change to that project’s directory, and build: $ git clone example.org/someproject $ cd someproject $ cargo build For more information about Cargo, check out its documentation at https://doc.rust-lang.org/cargo. Summary You’re already off to a great start on your Rust journey! In this chapter, you’ve learned how to: Install the latest stable version of Rust using rustup Update to a newer Rust version Open locally installed documentation Write and run a “Hello, world!” program using rustc directly Create and run a new project using the conventions of Cargo This is a great time to build a more substantial program to get used to reading and writing Rust code. So, in Chapter 2, we’ll build a guessing game program. If you would rather start by learning how common programming concepts work in Rust, see Chapter 3 and then return to Chapter 2.
  • 51. 2 PROGRAMMING A GUESSING GAME Let’s jump into Rust by working through a hands-on project together! This chapter introduces you to a few common Rust concepts by showing you how to use them in a real program. You’ll learn about let, match, methods, associated functions, external crates, and more! In the following chapters, we’ll explore these ideas in more detail. In this chapter, you’ll just practice the fundamentals. We’ll implement a classic beginner programming problem: a guessing game. Here’s how it works: the program will generate a random integer between 1 and 100. It will then prompt the player to enter a guess. After a guess is entered, the program will indicate whether the guess is too low or too high. If the guess is correct, the game will print a congratulatory message and exit. Setting Up a New Project To set up a new project, go to the projects directory that you created in Chapter 1 and make a new project using Cargo, like so: $ cargo new guessing_game $ cd guessing_game
  • 52. The first command, cargo new, takes the name of the project (guessing_game) as the first argument. The second command changes to the new project’s directory. Look at the generated Cargo.toml file: Cargo.toml [package] name = "guessing_game" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo /reference/manifest.html [dependencies] As you saw in Chapter 1, cargo new generates a “Hello, world!” program for you. Check out the src/main.rs file: src/main.rs fn main() { println!("Hello, world!"); } Now let’s compile this “Hello, world!” program and run it in the same step using the cargo run command: $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_game) Finished dev [unoptimized + debuginfo] target(s) in 1.50s Running `target/debug/guessing_game` Hello, world! The run command comes in handy when you need to rapidly iterate on a project, as we’ll do in this game, quickly testing each iteration before moving on to the next one. Reopen the src/main.rs file. You’ll be writing all the code in this file.
  • 53. Processing a Guess The first part of the guessing game program will ask for user input, process that input, and check that the input is in the expected form. To start, we’ll allow the player to input a guess. Enter the code in List ing 2-1 into src/main.rs. src/main.rs use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } Listing 2-1: Code that gets a guess from the user and prints it This code contains a lot of information, so let’s go over it line by line. To obtain user input and then print the result as output, we need to bring the io input/output library into scope. The io library comes from the standard library, known as std: use std::io; By default, Rust has a set of items defined in the standard library that it brings into the scope of every program. This set is called the prelude, and you can see everything in it at https://doc.rust-lang.or g/std/prelude/index.html. If a type you want to use isn’t in the prelude, you have to bring that type into scope explicitly with a use statement. Using the std::io
  • 54. library provides you with a number of useful features, including the ability to accept user input. As you saw in Chapter 1, the main function is the entry point into the program: fn main() { The fn syntax declares a new function; the parentheses, (), indicate there are no parameters; and the curly bracket, {, starts the body of the function. As you also learned in Chapter 1, println! is a macro that prints a string to the screen: println!("Guess the number!"); println!("Please input your guess."); This code is printing a prompt stating what the game is and requesting input from the user. Storing Values with Variables Next, we’ll create a variable to store the user input, like this: let mut guess = String::new(); Now the program is getting interesting! There’s a lot going on in this little line. We use the let statement to create the variable. Here’s another example: let apples = 5; This line creates a new variable named apples and binds it to the value 5. In Rust, variables are immutable by default, meaning once we give the variable a value, the value won’t change. We’ll be discussing this concept in detail in “Variables and Mutability” on page 32. To make a variable mutable, we add mut before the variable name:
  • 55. Random documents with unrelated content Scribd suggests to you:
  • 59. The Project Gutenberg eBook of Duell-Codex This ebook is for the use of anyone anywhere in the United States and most other parts of the world at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this ebook or online at www.gutenberg.org. If you are not located in the United States, you will have to check the laws of the country where you are located before using this eBook. Title: Duell-Codex Author: Gustav Hergsell Release date: March 26, 2017 [eBook #54438] Most recently updated: October 23, 2024 Language: German Credits: Produced by Harry Lamé and the Online Distributed Proofreading Team at http://www.pgdp.net (This file was produced from images generously made available by The Internet Archive) *** START OF THE PROJECT GUTENBERG EBOOK DUELL-CODEX ***
  • 60. Anmerkungen zur Transkription befinden sich am Ende dieses Textes. DUELL-CODEX. ZWEITE, ERGÄNZTE AUFLAGE.
  • 62. VON GUSTAV HERGSELL K. K. HAUPTMANN i. E., DIRECTOR DER KÖNIGL. LANDES-FECHTSCHULE ZU PRAG, RITTER DES KAISERL. OESTERREICH. FRANZ JOSEFS-ORDENS, DES KÖNIGL. SÄCHSISCHEN ALBRECHT-ORDENS I. CL., DES KÖNIGL. WÜRTTEMBERGISCHEN FRIEDRICH-ORDENS I. CL., DES SACHSEN ERNESTI-NISCHEN HAUSORDENS I. CL., BESITZER DES HERZOGL. SACHSEN-COBURG-GOTHA’SCHEN VERDIENST-ORDENS ERNST I. FÜR KUNST U. WISSENSCHAFT. ZWEITE, ERGÄNZTE AUFLAGE. MIT 7 TAFELN. WIEN. PEST. LEIPZIG. A. HARTLEBEN’S VERLAG. 1897.
  • 63. Alle Rechte vorbehalten. K. u. k. Hofbuchdruckerei Carl Fromme in Wien.
  • 64. Vorwort zur ersten Auflage. Das von meinen Schülern und vielen Freunden der Fechtkunst oft an mich gestellte Ersuchen, eine übersichtliche Zusammenstellung der Duellregeln zu verfassen und den Vorgang bei einem Ernstfalle kurz und bündig zu schildern, hat mich bewogen, die Ergebnisse meiner Beobachtungen und meines Studiums über diesen Gegenstand in dem vorliegenden Werke niederzulegen. Ich habe mich bei dieser Arbeit durch die Aufzeichnungen des Grafen Chatauvillard, seiner Mitarbeiter und Nachfolger, deren ich gegebenenfalls Erwähnung thue, leiten lassen; ich habe getrachtet, die dort veröffentlichten Vorschriften, von denen einige die Sache bloss streifen, für die gegenwärtigen Verhältnisse manchmal nicht mehr recht verständlich oder unvollendet sind, zu entwickeln, zu präcisiren und nach Möglichkeit zu vervollständigen. Wenngleich in den Einzelnheiten veraltet, bieten die von Chatauvillard aufgestellten Regeln, Vorschriften und Ansichten dennoch ein unschätzbares Material, und werden von allen Männern von Ehre respectirt, so lange nicht eine berufene Vereinigung von Ehrenmännern andere Vorschriften oder Gesetze verfasst. Zu allen Zeiten bis in die letzten Jahre haben sich nicht wenig Schriftsteller der undankbaren Aufgabe bemächtigt, gegen die Nothwendigkeit und die Gebräuche des Duelles aufzutreten, indem sie das Duell von dem dreifachen Gesichtspunkte: der Vernunft, der Moral und der gesellschaftlichen Sitten, zu beleuchten versuchten. Von der Wahrheit des Satzes: „Es giebt nur ein Mittel, das Duell abzuschaffen — man schaffe das Ehrgefühl ab” durchdrungen, habe ich bei der mir gestellten Aufgabe grundsätzlich alle Betrachtungen über das Duell beiseite gelassen und mich darauf beschränkt, im I.
  • 65. Theile die Vorschriften oder Gesetze des Duelles zusammenzufassen und im II. Theile den Vorgang im Terrain beim Kampfe selbst, in logischer Reihenfolge zu schildern. Nur ungern unterzog ich mich auf vielfachen Wunsch der Aufgabe, in einem III. Theile eine Schilderung der irregulären, sogenannten Ausnahmsduelle zu geben. Der Ursprung und die geschichtliche Entwickelung des Duelles wurde nicht berührt, weil beides nicht zur Sache gehört; Fragen über das Verhalten während des Kampfes selbst, gegenüber Fechtern oder Naturalisten, über Offensive oder Defensive, wurden nur so weit erörtert, als deren Behandlung bei Schilderung des Kampfes unausweichlich war. Was die Bezeichnung der von den Duellanten gewählten Vertreter als Zeugen oder Secundanten anbelangt, so darf ich wohl als bekannt voraussetzen, dass es ehedem einen Unterschied zwischen Zeugen und Secundanten gab. Diese waren in der Zeit des Ritterthums Kampfgenossen und hatten als solche wieder ihre Zeugen. Heute giebt es streng genommen nur Zeugen; diesen Namen führen auch die Vertreter der Gegner in Frankreich. In Deutschland werden beide Bezeichnungen abwechselnd gebraucht; bei uns in Oesterreich heissen die Vertrauensträger der Gegner fast allgemein Secundanten. Dieser Gepflogenheit habe auch ich mich angeschlossen. Wenn auch bei den einzelnen Arten des Zweikampfes die vorbereitenden Schritte im Terrain stets gleich sind und bei Darstellung derselben auf die allgemeinen Vorschriften verwiesen werden konnte, so fand ich mich dennoch veranlasst, um jede Duellart für sich allein in ihrer Entwickelung zu schildern, dieser allgemeinen Vorschriften stets in Kurzem zu erwähnen, wodurch einzelne Wiederholungen unvermeidlich waren. Weit entfernt, dass dieser Codex eine Aufmunterung zu unnöthigen, muthwilligen Duellen werde, soll er vielmehr allen Jenen, die durch die Umstände gezwungen sind, sich zu einer bewaffneten Begegnung zu stellen, als Richtschnur darüber dienen, wozu sie berechtigt und verpflichtet sind, andererseits aber Alle, die
  • 66. durch Vertrauen berufen werden, bei dem Kampfe zu interveniren, aber wenig Erfahrung für solche Vorgänge haben, lehren, dass es mitunter in ihrer Macht steht, ungünstige Wechselfälle des Kampfes bei vollkommener Wahrung der Ehre Dessen, den sie vertreten, zu verringern, wenn nicht hintanzuhalten. Ist es mir gelungen, das mir gesteckte Ziel zu erreichen, so ist mein Zweck erfüllt. In dieser Erwartung übergebe ich hiermit das vorliegende Werk der Oeffentlichkeit. Der Verfasser.
  • 67. Vorwort zur zweiten Auflage. Auf Grund der Erfahrungen, welche ich seit Ausgabe der ersten Auflage gemacht habe, sowie in Folge der mannigfachen an mich gestellten Anfragen in Beilegung und Austragung von Ehrenangelegenheiten, die ich alle nach Thunlichkeit zu berücksichtigen trachtete, wurden in dieser zweiten Auflage, speciell im ersten Theile jene Artikel einer gründlichen Bearbeitung durch Ergänzungen unterzogen, die ich zur rascheren Orientirung für besonders nothwendig erachtete. Besitzer der ersten Auflage werden in dieser neuen Ausgabe wesentliche Ergänzungen finden, die ihnen als weiterer Behelf zur Schlichtung von Ehrenangelegenheiten von Nutzen sein dürften. An dieser Stelle wollen wir auch des neueren französischen Fachschriftstellers A. Croabbon erwähnen, dessen interessantes Werk: „La science de point d’honneur” wir gegebenenfalls bei unseren Ergänzungen anführen. Bei dieser Gelegenheit sei nochmals darauf hingewiesen, dass die Bildtafeln lediglich für die Secundanten bestimmt sind. P r a g . Der Verfasser.
  • 69. I N H A L T . Seite Vorwort zur ersten Auflage V Vorwort zur zweiten Auflage VIII Einleitung 3 I. Theil. Von den Duellregeln im Allgemeinen 8 Vom Duell und der Beleidigung 11 Directe Beleidigung 13 Beleidigung ersten Grades 14 Einfache Beleidigung 14 Beleidigung zweiten Grades 15 Beleidigung durch Beschimpfung 15 Beleidigung dritten Grades 16 Beleidigung durch Schlag 16 Beleidigung durch ungerechte Beschuldigung 18 Grundlose Herausforderung 20 Indirecte Beleidigung 22 Rechte des Beleidigten und deren Zuerkennung 23 a) Beleidigung einer Person 23 b) Beleidigung einer Familie oder einer Corporation 26 Pflichten des Beleidigers 27 Die Forderung 28 Secundanten und ihre Pflichten 33 Beilegung des Duelles 51
  • 70. Ablehnung des Duelles 53 Gänzliche Ablehnung 54 An- oder Aberkennung der Satisfactionsfähigkeit durch einen Ehrenrath 58 Ehrenrath 60 Ablehnung einer bestimmten Duellart 62 Säbel oder Degen 62 Pistole 64 Stellvertretung und Verantwortlichkeit für Andere 65 Unfähigkeit oder Ausschliessung der Secundanten 69 Unterbrechung des Kampfes 71 Haltruf 71 Pause 75 Desarmirung 77 An die Wand drängen 79 Verletzung der Duellgesetze 81 Leibesvisitirung 83 Die Verwundung 84 Parade oder Opposition mit der linken Hand 88 Der Kampf 90 Austragung des Duelles 97 Nach dem Kampfe 99 Von den Ausnahmsduellen 101 II. Theil. Duellarten 108 Säbelduell 113 Beschaffenheit der Waffen 113 Bekleidung 114 Arten des Säbelduelles 116 I. Säbelduell ohne Stoss 116
  • 71. Vorgang auf dem Terrain 117 II. Säbelduell mit Stoss 129 Degenduell 129 Beschaffenheit der Waffen 129 Bekleidung 130 Vorgang auf dem Terrain 131 Pistolenduelle 143 Beschaffenheit der Waffen 150 Arten der Pistolenduelle 151 Bekleidung 152 Vorgang auf dem Terrain 153 I. Pistolenduell mit festem Standpunkte 153 II. Pistolenduell mit festem Standpunkte und freiem Schusse 160 III. Pistolenduell mit Vorrücken. — Barrièren 165 IV. Pistolenduell mit unterbrochenem Vorrücken 171 V. Pistolenduell auf parallelen Linien 175 VI. Pistolenduell auf Commando oder Signal 179 Revolver 186 III. Theil. Ausnahmsduelle 189 Arten des Ausnahmsduelles 191 Ausnahmsduell mit Pistolen 192 I. Pistolenduell mit festem Standpunkte bei geringerer als der gesetzmässig kürzesten Entfernung 192 II. Pistolenduell mit Vorrücken 195 Mit enger oder naher Barrière 195 Mit einer Barrière 196 III. Duell mit e i n e r geladenen Pistole 196
  • 72. IV. Pistolenduell auf parallelen Linien mit ununterbrochenem Vorrücken 200 Kampf mit Gewehr 204 Kampf mit Carabiner 205 Kampf zu Pferde 205 Amerikanisches Duell 206 Anhang. Muster für die Abfassung von Protokollen 211 I. Schriftliche Vereinbarung der Secundanten 211 A. Bei Beleidigung ersten Grades 213 B. Beilegung des Duelles nach einer Beschimpfung 214 II. Protokoll über den stattgefundenen Zweikampf 216
  • 73. VERZEICHNIS DER TAFELN. Seite I. Säbelduell 115 II. Degenduell 128 III. Pistolenduell mit festem Standpunkte 153 IV. Pistolenduell mit festem Standpunkte und freiem Schusse 160 V. Pistolenduell mit Vorrücken. — Barrièren 165 VI. Pistolenduell mit unterbrochenem Vorrücken 171 VII. Pistolenduell auf parallelen Linien 175 DUELL-CODEX.
  • 74. EINLEITUNG. Der Zweikampf steht ausserhalb des Gesetzes, keine seiner Regeln kann den Charakter der Legalität in der gewöhnlichen Auffassung dieses Wortes beanspruchen. Dennoch zögern wir nicht, jenen Regeln den Namen „Duellcodex” beizulegen. Wenn es wahr ist, was thatsächlich unter allen civilisirten Völkern mit Recht zugegeben wird, dass die Ehre ebenso unantastbar ist wie die Gesetze, so sind die Vorschriften über die zum Schutze der gekränkten Ehre zu beobachtenden Vorgänge von keinem geringeren Ansehen als jene. Der Grund, dass die staatlichen Gesetze den Zweikampf ausserhalb ihres Rahmens verweisen, liegt in der Unzulässigkeit der Selbsthilfe. An deren Stelle ist in einem geordneten Gemeinwesen die staatliche Hilfe gesetzt, damit der Schwache nicht Unrecht erdulden müsse von dem Starken. Allein ganz abgesehen davon, dass die Selbsthilfe nicht überall verwerflich ist, wie uns die Zulässigkeit der Nothwehr und des Besitzschutzes bezeugen, ist nicht zu übersehen, dass die Gesetze Männern mit hochentwickeltem Ehrgefühl nach deren Ueberzeugung bisweilen nicht ausreichenden Schutz gegen ihnen selbst oder ihnen nahestehenden Personen widerfahrenen Unbilden gewähren. Von diesem Standpunkte erscheint daher das Duell weder anormal, noch unbegreiflich, noch unmoralisch. „Jeder,” sagt uns Graf Chatauvillard, „ist der herben Nothwendigkeit unterworfen, sein Leben zu wagen, um wegen einer Beleidigung oder Beschimpfung Rechenschaft zu verlangen.” Die Sache ist daher nach der Meinung desselben Autors im menschlichen Leben wichtig genug, um im Vorhinein nach
  • 75. Unparteilichkeit und Ehrgefühl geordnet zu werden, zumal die sich täglich erneuernden Beispiele das Bedürfnis darnach erweisen. So werden diese Regeln zum Schutze für Alle als Schranken wider Ueberfall und Rachsucht und können selbst als ein Ausfluss der Cultur und ritterlicher Gesittung angesehen werden, welche die Feststellung derselben als begründet erscheinen lässt. Diese Vorschriften haben sich aus dem Herkommen, dem Gebrauche und aus der Ueberzeugung gleichgesinnter Kreise von der Nothwendigkeit dieses Gebrauches herausgebildet, beruhen also auf denselben rechtserzeugenden Grundlagen wie das Gewohnheitsrecht. Einzig und allein in diesem eingeschränkten Sinne betrachtet man jene Duellarten, die den herkömmlichen Vorschriften entsprechen, als „legale”. Wird hiervon auch nur in einzelnen Punkten abgewichen, so steht das Duell auch ausserhalb des Herkommens und heisst „Ausnahmsduell” (exceptionelles Duell). Graf Chatauvillard, Mitglied des Pariser Jockey-Club, hat in Folge einer an ihn gerichteten Aufforderung im Vereine der weiteren Mitglieder General Graf Excelmans, Grafen du Hallay-Coëtquen, General Baron Gourgaud, Brivois und des Vicomte de Contades sich der Aufgabe unterzogen, die Gebräuche und Vorschriften des Duelles zu fixiren, die unter dem Titel „Essai sur le duel” im Jahre 1836 zu Paris erschienen. Dieses Werk wurde nicht nur in Paris von der öffentlichen Meinung lebhaft begrüsst, sondern jene Vorschriften haben sich auch bald ausserhalb Frankreich Geltung verschafft, da sie durch die Signatur hervorragender Mitglieder der Pariser Gesellschaft sanctionirt wurden. Ueberzeugt, dass es von allgemeinem Interesse sein dürfte, die Namen dieser Mitarbeiter kennen zu lernen, wollen wir dieselben anführen. Die Unterschrift wurde mit folgenden Worten eingeleitet: „Innig überzeugt, dass die Intentionen des Verfassers, weit entfernt die Duelle zu protegiren, im Gegentheil dahin streben, ihre Zahl zu vermindern, sie zu regeln und ihren verderblichen Charakter zu verringern, geben die Unterzeichneten den in diesem Werke
  • 76. aufgestellten und auseinandergesetzten Vorschriften ihre volle Genehmigung.” Marschall Graf de Lobau, Pair von Frankreich. Marschall Graf Molitor, Pair von Frankreich. Viceadmiral Marquis de Sercey, Pair von Frankreich. Generallieutenant Herzog de Guiche. Generallieutenant Graf Dutaillis, Pair von Frankreich. Generallieutenant Herzog de Doudeauville. Generallieutenant Graf de la Grange, Pair von Frankreich. Generallieutenant Vicomte de Cavaignac. General de Fourolles. Generallieutenant Graf de la Houssay. General Graf Friaut. Generallieutenant Baron Billard. Generallieutenant Graf Claparède, Pair von Frankreich. General Graf Clary. General Miot. General A. de Saint-Yon. Generallieutenant Pierre Boyer. General L. Bernard. Generallieutenant Graf Merlin. Generallieutenant Graf Villaret de Joyeuse. Generallieutenant de Solignac. General Vicomte de Maucomble. Generallieutenant Baron Gourgaud. Generallieutenant Excelmans, Pair von Frankreich. Oberst de Rossi. Oberst L. Brack. Oberst de Garaube. Oberstlieutenant Graf de Maussion. Oberstlieutenant R. de Grandmont. Oberstlieutenant J. Combe. Oberstlieutenant de Casanova. Oberstlieutenant de Lherminier. Oberstlieutenant Baron E. de Marguerittes. Oberst der Nationalgarde Graf de Lariboissière, Pair von
  • 77. Frankreich. Oberst der Nationalgarde Le Mercier. Herzog d’Istrie, Pair von Frankreich. Herzog de Saulx Tavannes, Pair von Frankreich. Prinz Alex. de Wagram, Pair von Frankreich. Escadronschef Graf von Sercey. Capitaine Graf von Grabowski. Louis Paira. Prinz Poniatowski. Graf de Plaisance. Vicomte Daure. Marquis de Bellemont. Vicomte Curial. Graf de Montholon. Vicomte Walch. De Messimieux. Commandant Graf Ch. de Nieuwerkerke. Du Suau de la Croix. Capitaine Marquis de Livry. G. de Martignac. Gaetan Murat. Graf von Pontcarré. Marquis de Quémadeuc. Ed. Faye. Baron d’Aubigny. Capitaine Graf Walewsky. Ed. Adam. Capitaine E. d’Hervas. G. de la Rifaudière. Graf de Clermont-Mont-Saint-Jean. Capitaine Graf de Clerembault. Graf de Langle. Merle. Vicomte Dutaillis. Commandant Graf de Walewski. A. Dufougerais.
  • 78. Phil. Martines. M. Delaunay. Graf J. de la Grange. Baron de Préjan. Brivois. Vicomte de Contades. Graf du Hallay-Coëtquen. Zum Schlusse findet sich die Bemerkung: „Der Herr Kriegsminister, die Herren Präfecten etc. etc. haben als Männer das gebilligt, was sie als Beamte nicht unterzeichnen konnten.”
  • 79. I. Theil. Von den Duellregeln im Allgemeinen. Vom Duell und der Beleidigung. Jedes Wort, jede Schrift, Absicht oder Geste, welche die Eigenliebe, Zartgefühl oder Ehre eines Zweiten verletzt, ist für diesen eine Beleidigung. Die Nuancen der Beleidigungen gehen ins Unendliche; es lässt sich der Werth derselben schwer feststellen, es wird schwierig, die verschiedenen Beleidigungen zu definiren. Die Beleidigung ist Gefühlssache, denn jeder fühlt auf verschiedene Art und Weise; dies hängt meist mit der socialen Stellung zusammen. Wenn aber eine Eintheilung, eine Beurtheilung der Beleidigung stattfinden soll, dann hat diese in der Weise vorgenommen zu werden, dass die entehrende Beschimpfung, und vor allem der Schlag, abgesondert wird.
  • 80. Um sich für eine Beleidigung Genugthuung zu verschaffen, um den Angriff gegen seine Person zurückzuweisen, greift man zu den Waffen — erfolgt das Duell. Man schlägt sich, um für eine Beleidigung persönlich Genugthuung zu geben oder diese zu erhalten. Erfolgt die Beleidigung ohne Grund, so ist dies allerdings ein beklagenswerther Umstand, und das Unrecht ist auf Seite des Provocirenden, aber er allein hat sich hierüber Rechenschaft zu geben; um dieses Unrecht zu sühnen, setzt er im Waffengange, im Duell, sein Leben ein. Der Beweggrund, durch welchen das Duell — der Zweikampf — herbeigeführt wurde, ist gleichgiltig. Das Duell ist demnach ein zwischen zwei Personen stattfindender verabredeter Kampf, welche in diesem, also durch Hilfenahme der Waffen, das Mittel suchen, ausserhalb des Gesetzes eine Differenz zu begleichen, oder sich durch diese Gerechtigkeit zu verschaffen. Es ist ein auf Basis gesetzmässiger Regeln und vorher getroffener Vereinbarungen, in Gegenwart von Zeugen, mit g l e i c h a r t i g e n , t ö d t l i c h e n Waffen stattfindender Zweikampf. Wenn daher die beiden Gegner das Uebereinkommen getroffen haben, gleichgiltig ob ausdrücklich oder stillschweigend, den Gesetzen der Ehre nur scheinbar Genüge zu leisten — entweder auf Zeitdauer sich der blanken Waffen zu bedienen, ohne ernstlich angreifen zu wollen, oder beiderseits bei einem Pistolenduell in die Luft zu schiessen u. s. w. — so ist dieses kein Zweikampf, kein Duell. Die gesetzmässigen Regeln verlangen g l e i c h a r t i g e Waffen, damit nicht im Vorhinein der Sieg zu Gunsten des einen oder des anderen der beiden Combattanten entschieden wird. Aus diesem erhellt, dass den beiden Gegnern auch die Möglichkeit geboten werden muss, durch ihr gegenseitiges Einsetzen von Kraft und Geschicklichkeit aus dem Kampfe als Sieger hervorgehen zu können. Es kann daher in bestimmten Fällen die Ablehnung einer bestimmten Duellart stattfinden.
  • 81. So steht bei gewissen Graden der Beleidigung den Secundanten das Recht zu, die Annahme eines Säbel- oder Degenduelles zu verweigern, falls der rechte Arm ihres Clienten derart strupirt ist, dass der freie Gebrauch der Waffe gehindert erscheint; ebenso können die Secundanten eines Einäugigen ein Pistolenduell verweigern. Weiters verlangt das Gesetz t ö d t l i c h e Waffen. Ein Kampf mit „tödtlichen” Waffen liegt nicht vor, wenn die Waffen im Vorhinein eine ernste Verwundung ausschliessen, oder die Combattanten derartige Schutzmassregeln in Anwendung bringen, die eine schwere, lebensgefährliche Verwundung nicht zulassen. Es ist daher ein Faustkampf ebenso wenig ein Zweikampf — ein Duell — wie das Boxen der Engländer. Aber auch die Waffen müssen den hergebrachten Sitten, den Duellgesetzen entsprechen. Messer, Dolche, Handschare, Lanzen sind ebenso wenig Duellwaffen, wie Stöcke oder dergleichen ähnliche, für einen Ueberfall oder für die Nothwehr bestimmte Waffen. Erfolgt der Kampf mit beiderseitiger Uebereinstimmung auf der Stelle, oder auch später, mit oder ohne vorher gepflogenen Vereinbarungen, aber ohne Zeugen oder Secundanten, so wird dieser Zweikampf weder von der öffentlichen Meinung, noch vor dem Gesetze als ein legales Duell angesehen. Dieses Zusammentreffen führt den Namen Rencontre. Der Kampf muss ein auf Basis vorher getroffener Vereinbarungen verabredeter sein, wobei es gleichgiltig erscheint, ob den Vereinbarungen längere oder kürzere Verhandlungen zu Grunde liegen. N u r a u f G r u n d e i n e r s t a t t g e f u n d e n e n o d e r v e r m e i n t l i c h e n B e l e i d i g u n g s o l l e i n e H e r a u s f o r d e r u n g , e i n D u e l l e r f o l g e n . Die Beleidigungen können im Allgemeinen in zwei Gruppen gefasst werden: 1. Directe Beleidigungen. 2. Indirecte Beleidigungen.
  • 82. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com