Rust by example.pdf

(1749 KB) Pobierz
Rust By Example
https://rustbyexample.com/print.html
Rust by Example
Rust
is a modern systems programming language focusing on safety, speed, and
concurrency. It accomplishes these goals by being memory safe without using
garbage collection.
Rust by Example (RBE) is a collection of runnable examples that illustrate various
Rust concepts and standard libraries. To get even more out of these examples,
don't forget to
install Rust locally
and check out the
o�½cial docs.
Additionally for
the curious, you can also
check out the source code for this site.
Now let's begin!
Hello World
- Start with a traditional Hello World program.
Primitives
- Learn about signed integers, unsigned integers and other
primitives.
Custom Types
-
struct
and
enum
.
Variable Bindings
- mutable bindings, scope, shadowing.
Types
- Learn about changing and de�½ning types.
Conversion
Expressions
Flow Control
-
if
/
else
,
for
, and others.
Functions
- Learn about Methods, Closures and High Order Functions.
Modules
- Organize code using modules
Crates
- A crate is a compilation unit in Rust. Learn to create a library.
Attributes
- An attribute is metadata applied to some module, crate or item.
Generics
- Learn about writing a function or data type which can work for
multiple types of arguments.
Scoping rules
- Scopes play an important part in ownership, borrowing, and
lifetimes.
1 of 182
10/28/17, 10:44 PM
Rust By Example
https://rustbyexample.com/print.html
Traits
- A trait is a collection of methods de�½ned for an unknown type:
Self
Macros
Error handling
- Learn Rust way of handling failures.
Std library types
- Learn about some custom types provided by
std
library.
Std misc
- More custom types for �½le handling, threads.
Meta
- Documentation, Testing
Unsafe Operations
Hello World
This is the source code of the traditional Hello World program.
// This is a comment, and will be ignored by the compiler
// You can test this code by clicking the "Run" button over there ->
// or if prefer to use your keyboard, you can use the "Ctrl + Enter" shortcut
// This code is editable, feel free to hack it!
// You can always return to the original code by clicking the "Reset" button ->
// This is the main function
fn
main() {
// The statements here will be executed when the compiled binary is called
// Print text to the console
println!("Hello
World!");
 
}
println!
is a
macro
that prints text to the console.
A binary can be generated using the Rust compiler:
rustc
.
$ rustc hello.rs
rustc
will produce a
hello
binary that can be executed.
$ ./hello
Hello World!
Activity
Click 'Run' above to see the expected output. Next, add a new line with a second
2 of 182
10/28/17, 10:44 PM
Rust By Example
https://rustbyexample.com/print.html
println!
macro so that the output shows:
Hello World!
I'm a Rustacean!
Comments
Any program requires comments and indeed Rust supports a few di�½erent
varieties:
Regular comments
which are ignored by the compiler:
// Line comments which go to the end of the line.
/* Block comments which go to the closing delimiter. */
Doc comments
which are parsed into HTML library
documentation:
/// Generate library docs for the following item.
//! Generate library docs for the enclosing item.
fn
main() {
// This is an example of a line comment
// Notice how there are two slashes at the beginning of the line
// And that nothing written inside these will be read by the compiler
// println!("Hello, world!");
// Run it. See? Now try deleting the two slashes, and run it again.
/*
* This is another type of comment, the block comment. In general,
* the line comment is the recommended comment style however the
* block comment is extremely useful for temporarily disabling
* a large chunk of code. /* Block comments can be /* nested, */ */
* so it takes only a few keystrokes to comment out all the lines
* in this main() function. /*/*/* Try it yourself! */*/*/
*/
/*
Note, the previous column of `*` was entirely for style. There's
no actual need for it.
*/
// Observe how block comments allow easy expression manipulation
// which line comments do not. Deleting the comment delimiters
// will change the result:
let
x
=
5
+
/* 90 + */
5;
println!("Is
`x` 10 or 100? x = {}",
x);
 
}
See also:
3 of 182
10/28/17, 10:44 PM
Rust By Example
https://rustbyexample.com/print.html
Library documentation
Formatted print
Printing is handled by a series of
macros
de�½ned in
std::fmt
some of which
include:
format!
: write formatted text to
String
print!
: same as
format!
but the text is printed to the console.
println!
: same as
print!
but a newline is appended.
All parse text in the same fashion. A plus is that the formatting correctness will be
checked at compile time.
fn
main() {
// In general, the `{}` will be automatically replaced with any
// arguments. These will be stringified.
println!("{}
days",
31);
// Without a suffix, 31 becomes an i32. You can change what type 31 is,
// with a suffix.
// There are various optional patterns this works with. Positional
// arguments can be used.
println!("{0},
this is {1}. {1}, this is {0}", "Alice", "Bob");
// As can named arguments.
println!("{subject}
{verb} {object}",
object="the
lazy dog",
subject="the
quick brown fox",
verb="jumps
over");
// Special formatting can be specified after a `:`.
println!("{}
of {:b} people know binary, the other half doesn't",
1, 2);
// You can right-align text with a specified width. This will output
// "
1". 5 white spaces and a "1".
println!("{number:>width$}", number=1, width=6);
// You can pad numbers with extra zeroes. This will output "000001".
println!("{number:>0width$}", number=1, width=6);
// It will even check to make sure the correct number of arguments are
// used.
println!("My
name is {0}, {1} {0}", "Bond");
// FIXME ^ Add the missing argument: "James"
// Create a structure which contains an `i32`. Name it `Structure`.
#[allow(dead_code)]
struct
Structure(i32);
// However, custom types such as this structure require more complicated
// handling. This will not work.
println!("This
struct `{}` won't print...",
Structure(3));
// FIXME ^ Comment out this line.
 
}
4 of 182
10/28/17, 10:44 PM
Rust By Example
https://rustbyexample.com/print.html
std::fmt
contains many
traits
which govern the display of text. The base form
of two important ones are listed below:
fmt::Debug
: Uses the
{:?}
marker. Format text for debugging purposes.
fmt::Display
: Uses the
{}
marker. Format text in a more elegant, user
friendly fashion.
Here,
fmt::Display
was used because the std library provides implementations
for these types. To print text for custom types, more steps are required.
Activities
Fix the two issues in the above code (see FIXME) so that it runs without error.
Add a
println!
macro that prints:
Pi is roughly 3.142
by controlling the
number of decimal places shown. For the purposes of this exercise, use
let pi = 3.141592
as an estimate for Pi. (Hint: you may need to check the
std::fmt
documentation for setting the number of decimals to display)
See also
std::fmt
,
macros
,
struct
, and
traits
Debug
All types which want to use
std::fmt
formatting
traits
require an
implementation to be printable. Automatic implementations are only provided for
types such as in the
std
library. All others
must
be manually implemented
somehow.
The
fmt::Debug trait
makes this very straightforward.
All
types can
derive
(automatically create) the
fmt::Debug
implementation. This is not true for
fmt::Display
which must be manually implemented.
5 of 182
10/28/17, 10:44 PM
Zgłoś jeśli naruszono regulamin