diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c791f03..26d3928 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,7 +20,7 @@ cd rust-cookbook Cookbook is built with [mdBook], so install that first with Cargo: ``` -cargo install --version 0.1.8 mdbook +cargo install --version 0.3.5 mdbook ``` To build and view the cookbook locally, run: diff --git a/Cargo.toml b/Cargo.toml index efc2817..98a9847 100755 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,6 +2,7 @@ name = "rust-cookbook" version = "0.1.0" authors = ["Brian Anderson "] +edition = "2018" license = "MIT/Apache-2.0" publish = false @@ -9,6 +10,7 @@ build = "build.rs" [dependencies] ansi_term = "0.11.0" +approx = "0.3" base64 = "0.9" bitflags = "1.0" byteorder = "1.0" @@ -58,7 +60,7 @@ url = "2.1" walkdir = "2.0" [target.'cfg(target_os = "linux")'.dependencies] -syslog = "4.0" +syslog = "5.0" [build-dependencies] skeptic = "0.13" diff --git a/README.md b/README.md index 61d5a04..189990f 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ If you'd like to read it locally: ```bash $ git clone https://github.com/rust-lang-nursery/rust-cookbook $ cd rust-cookbook -$ cargo install mdbook --vers "0.1.8" +$ cargo install mdbook --vers "0.3.5" $ mdbook serve --open ``` diff --git a/book.toml b/book.toml index 3e35329..8b3bb14 100644 --- a/book.toml +++ b/book.toml @@ -3,12 +3,14 @@ title = "Rust Cookbook" description = "Collection of useful Rust code examples" authors = ["Rust Language Community"] +edition = "2018" multilingual = false +language = "en" src = "src" [output.html] mathjax-support = false -theme = "theme" +# theme = "theme" additional-css = ["theme/custom.css"] [output.html.playpen] diff --git a/ci/install_deps.sh b/ci/install_deps.sh index b420597..562a8f5 100755 --- a/ci/install_deps.sh +++ b/ci/install_deps.sh @@ -18,7 +18,7 @@ if [[ "${CONTENT_TESTS:-}" == 1 ]]; then pyenv local 3.6.0 pip3 install --user link-checker==0.1.0 fi - cargo install mdbook --vers '0.1.8' --debug + cargo install mdbook --vers '0.3.5' --debug fi exit 0 diff --git a/src/about.md b/src/about.md index c59461a..e1d0b70 100644 --- a/src/about.md +++ b/src/about.md @@ -56,8 +56,7 @@ Consider this example for "generate random numbers within a range": [![rand-badge]][rand] [![cat-science-badge]][cat-science] -```rust -extern crate rand; +```rust,edition2018 use rand::Rng; fn main() { @@ -111,10 +110,8 @@ The basic pattern we use is to have a `fn main() -> Result`. The structure generally looks like: -```rust -#[macro_use] -extern crate error_chain; - +```rust,edition2018 +use error_chain::error_chain; use std::net::IpAddr; use std::str; @@ -150,10 +147,8 @@ default like below. In order to read full contents click on the "expand" () button located in the top right corner of the snippet. -```rust -# #[macro_use] -# extern crate error_chain; -extern crate url; +```rust,edition2018 +# use error_chain::error_chain; use url::{Url, Position}; # diff --git a/src/algorithms/randomness/rand-choose.md b/src/algorithms/randomness/rand-choose.md index acb61fe..b895139 100644 --- a/src/algorithms/randomness/rand-choose.md +++ b/src/algorithms/randomness/rand-choose.md @@ -5,9 +5,7 @@ Randomly generates a string of given length ASCII characters with custom user-defined bytestring, with [`gen_range`]. -```rust -extern crate rand; - +```rust,edition2018 fn main() { use rand::Rng; const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ diff --git a/src/algorithms/randomness/rand-custom.md b/src/algorithms/randomness/rand-custom.md index 57ea967..8cf4324 100644 --- a/src/algorithms/randomness/rand-custom.md +++ b/src/algorithms/randomness/rand-custom.md @@ -5,9 +5,7 @@ Randomly generates a tuple `(i32, bool, f64)` and variable of user defined type `Point`. Implements the [`Distribution`] trait on type Point for [`Standard`] in order to allow random generation. -```rust,ignore -extern crate rand; - +```rust,edition2018,ignore use rand::Rng; use rand::distributions::{Distribution, Standard}; diff --git a/src/algorithms/randomness/rand-dist.md b/src/algorithms/randomness/rand-dist.md index 0655d1a..a5f6159 100644 --- a/src/algorithms/randomness/rand-dist.md +++ b/src/algorithms/randomness/rand-dist.md @@ -12,10 +12,7 @@ generator [`rand::Rng`]. The [distributions available are documented here][rand-distributions]. An example using the [`Normal`] distribution is shown below. -```rust,ignore -extern crate rand_distr; -extern crate rand; - +```rust,edition2018,ignore use rand_distr::{Distribution, Normal, NormalError}; fn main() -> Result<(), NormalError> { diff --git a/src/algorithms/randomness/rand-passwd.md b/src/algorithms/randomness/rand-passwd.md index 3968879..d193cf6 100644 --- a/src/algorithms/randomness/rand-passwd.md +++ b/src/algorithms/randomness/rand-passwd.md @@ -5,9 +5,7 @@ Randomly generates a string of given length ASCII characters in the range `A-Z, a-z, 0-9`, with [`Alphanumeric`] sample. -```rust,ignore -extern crate rand; - +```rust,edition2018,ignore use rand::{thread_rng, Rng}; use rand::distributions::Alphanumeric; diff --git a/src/algorithms/randomness/rand-range.md b/src/algorithms/randomness/rand-range.md index 6de6d16..ddc4f9c 100644 --- a/src/algorithms/randomness/rand-range.md +++ b/src/algorithms/randomness/rand-range.md @@ -4,9 +4,7 @@ Generates a random value within half-open `[0, 10)` range (not including `10`) with [`Rng::gen_range`]. -```rust,ignore -extern crate rand; - +```rust,edition2018,ignore use rand::Rng; fn main() { @@ -20,9 +18,7 @@ fn main() { This has the same effect, but may be faster when repeatedly generating numbers in the same range. -```rust,ignore -extern crate rand; - +```rust,edition2018,ignore use rand::distributions::{Distribution, Uniform}; diff --git a/src/algorithms/randomness/rand.md b/src/algorithms/randomness/rand.md index 01fdd82..6a8724e 100644 --- a/src/algorithms/randomness/rand.md +++ b/src/algorithms/randomness/rand.md @@ -8,9 +8,7 @@ initialized generator. Integers are uniformly distributed over the range of the type, and floating point numbers are uniformly distributed from 0 up to but not including 1. -```rust -extern crate rand; - +```rust,edition2018 use rand::Rng; fn main() { diff --git a/src/algorithms/sorting/sort.md b/src/algorithms/sorting/sort.md index ce2ad65..197a26a 100644 --- a/src/algorithms/sorting/sort.md +++ b/src/algorithms/sorting/sort.md @@ -6,7 +6,7 @@ This example sorts a Vector of integers via [`vec::sort`]. Alternative would be to use [`vec::sort_unstable`] which can be faster, but does not preserve the order of equal elements. -```rust +```rust,edition2018 fn main() { let mut vec = vec![1, 5, 10, 2, 15]; diff --git a/src/algorithms/sorting/sort_float.md b/src/algorithms/sorting/sort_float.md index 1413237..278b715 100644 --- a/src/algorithms/sorting/sort_float.md +++ b/src/algorithms/sorting/sort_float.md @@ -4,7 +4,7 @@ A Vector of f32 or f64 can be sorted with [`vec::sort_by`] and [`PartialOrd::partial_cmp`]. -```rust +```rust,edition2018 fn main() { let mut vec = vec![1.1, 1.15, 5.5, 1.123, 2.0]; diff --git a/src/algorithms/sorting/sort_struct.md b/src/algorithms/sorting/sort_struct.md index 851fb01..ba73298 100644 --- a/src/algorithms/sorting/sort_struct.md +++ b/src/algorithms/sorting/sort_struct.md @@ -7,7 +7,7 @@ order (By name and age). In order to make Person sortable you need four traits [ [`PartialEq`], [`Ord`] and [`PartialOrd`]. These traits can be simply derived. You can also provide a custom comparator function using a [`vec:sort_by`] method and sort only by age. -```rust +```rust,edition2018 #[derive(Debug, Eq, Ord, PartialEq, PartialOrd)] struct Person { name: String, diff --git a/src/cli/ansi_terminal/ansi_term-basic.md b/src/cli/ansi_terminal/ansi_term-basic.md index e1c8550..34e2f29 100644 --- a/src/cli/ansi_terminal/ansi_term-basic.md +++ b/src/cli/ansi_terminal/ansi_term-basic.md @@ -10,9 +10,7 @@ There are two main data structures in [`ansi_term`]: [`ANSIString`] and [`Style` ### Printing colored text to the Terminal -```rust -extern crate ansi_term; - +```rust,edition2018 use ansi_term::Colour; fn main() { @@ -29,9 +27,7 @@ For anything more complex than plain foreground colour changes, the code needs to construct `Style` struct. [`Style::new()`] creates the struct, and properties chained. -```rust -extern crate ansi_term; - +```rust,edition2018 use ansi_term::Style; fn main() { @@ -43,9 +39,7 @@ fn main() { `Colour` implements many similar functions as `Style` and can chain methods. -```rust -extern crate ansi_term; - +```rust,edition2018 use ansi_term::Colour; use ansi_term::Style; diff --git a/src/cli/arguments/clap-basic.md b/src/cli/arguments/clap-basic.md index 3b66e49..0dbcafa 100644 --- a/src/cli/arguments/clap-basic.md +++ b/src/cli/arguments/clap-basic.md @@ -11,9 +11,7 @@ use to retrieve the value passed. The `short` and `long` options control the flag the user will be expected to type; short flags look like `-f` and long flags look like `--file`. -```rust -extern crate clap; - +```rust,edition2018 use clap::{Arg, App}; fn main() { diff --git a/src/compression/tar/tar-compress.md b/src/compression/tar/tar-compress.md index dc74560..25735a6 100644 --- a/src/compression/tar/tar-compress.md +++ b/src/compression/tar/tar-compress.md @@ -10,9 +10,7 @@ under `backup/logs`path with [`Builder::append_dir_all`]. [`GzEncoder`] is responsible for transparently compressing the data prior to writing it into `archive.tar.gz`. -```rust,no_run -extern crate tar; -extern crate flate2; +```rust,edition2018,no_run use std::fs::File; use flate2::Compression; diff --git a/src/compression/tar/tar-decompress.md b/src/compression/tar/tar-decompress.md index 9eb14eb..324af29 100644 --- a/src/compression/tar/tar-decompress.md +++ b/src/compression/tar/tar-decompress.md @@ -7,9 +7,7 @@ extract ([`Archive::unpack`]) all files from a compressed tarball named `archive.tar.gz` located in the current working directory to the same location. -```rust,no_run -extern crate flate2; -extern crate tar; +```rust,edition2018,no_run use std::fs::File; use flate2::read::GzDecoder; diff --git a/src/compression/tar/tar-strip-prefix.md b/src/compression/tar/tar-strip-prefix.md index 27e840b..a770871 100644 --- a/src/compression/tar/tar-strip-prefix.md +++ b/src/compression/tar/tar-strip-prefix.md @@ -6,12 +6,8 @@ Iterate over the [`Archive::entries`]. Use [`Path::strip_prefix`] to remove the specified path prefix (`bundle/logs`). Finally, extract the [`tar::Entry`] via [`Entry::unpack`]. -```rust,no_run -# #[macro_use] -# extern crate error_chain; -extern crate flate2; -extern crate tar; - +```rust,edition2018,no_run +# use error_chain::error_chain; use std::fs::File; use std::path::PathBuf; use flate2::read::GzDecoder; diff --git a/src/concurrency/parallel/rayon-any-all.md b/src/concurrency/parallel/rayon-any-all.md index 5d4d361..3c4361e 100644 --- a/src/concurrency/parallel/rayon-any-all.md +++ b/src/concurrency/parallel/rayon-any-all.md @@ -4,9 +4,7 @@ This example demonstrates using the [`rayon::any`] and [`rayon::all`] methods, which are parallelized counterparts to [`std::any`] and [`std::all`]. [`rayon::any`] checks in parallel whether any element of the iterator matches the predicate, and returns as soon as one is found. [`rayon::all`] checks in parallel whether all elements of the iterator match the predicate, and returns as soon as a non-matching element is found. -```rust -extern crate rayon; - +```rust,edition2018 use rayon::prelude::*; fn main() { diff --git a/src/concurrency/parallel/rayon-iter-mut.md b/src/concurrency/parallel/rayon-iter-mut.md index 9bf4915..3431f93 100644 --- a/src/concurrency/parallel/rayon-iter-mut.md +++ b/src/concurrency/parallel/rayon-iter-mut.md @@ -6,9 +6,7 @@ The example uses the `rayon` crate, which is a data parallelism library for Rust `rayon` provides the [`par_iter_mut`] method for any parallel iterable data type. This is an iterator-like chain that potentially executes in parallel. -```rust -extern crate rayon; - +```rust,edition2018 use rayon::prelude::*; fn main() { diff --git a/src/concurrency/parallel/rayon-map-reduce.md b/src/concurrency/parallel/rayon-map-reduce.md index b5a2aa0..17a1a5f 100644 --- a/src/concurrency/parallel/rayon-map-reduce.md +++ b/src/concurrency/parallel/rayon-map-reduce.md @@ -11,9 +11,7 @@ new iteration, and [`rayon::reduce`] performs an operation given the previous reduction and the current element. Also shows use of [`rayon::sum`], which has the same result as the reduce operation in this example. -```rust -extern crate rayon; - +```rust,edition2018 use rayon::prelude::*; struct Person { diff --git a/src/concurrency/parallel/rayon-parallel-search.md b/src/concurrency/parallel/rayon-parallel-search.md index 71e6f41..173ecc3 100644 --- a/src/concurrency/parallel/rayon-parallel-search.md +++ b/src/concurrency/parallel/rayon-parallel-search.md @@ -12,9 +12,7 @@ necessarily the first one. Also note that the argument to the closure is a reference to a reference (`&&x`). See the discussion on [`std::find`] for additional details. -```rust -extern crate rayon; - +```rust,edition2018 use rayon::prelude::*; fn main() { diff --git a/src/concurrency/parallel/rayon-parallel-sort.md b/src/concurrency/parallel/rayon-parallel-sort.md index cb79212..971aa2d 100644 --- a/src/concurrency/parallel/rayon-parallel-sort.md +++ b/src/concurrency/parallel/rayon-parallel-sort.md @@ -9,9 +9,7 @@ values in parallel. Although [multiple options] exist to sort an enumerable data type, [`par_sort_unstable`] is usually faster than [stable sorting] algorithms. -```rust,ignore -extern crate rand; -extern crate rayon; +```rust,edition2018,ignore use rand::{Rng, thread_rng}; use rand::distributions::Alphanumeric; diff --git a/src/concurrency/parallel/rayon-thumbnails.md b/src/concurrency/parallel/rayon-thumbnails.md index 9aa0d3f..abf2db6 100644 --- a/src/concurrency/parallel/rayon-thumbnails.md +++ b/src/concurrency/parallel/rayon-thumbnails.md @@ -8,12 +8,8 @@ then saves them in a new folder called `thumbnails`. [`glob::glob_with`] finds jpeg files in current directory. `rayon` resizes images in parallel using [`par_iter`] calling [`DynamicImage::resize`]. -```rust,no_run -# #[macro_use] -# extern crate error_chain; -extern crate glob; -extern crate image; -extern crate rayon; +```rust,edition2018,no_run +# use error_chain::error_chain; use std::path::Path; use std::fs::create_dir_all; @@ -38,7 +34,7 @@ fn main() -> Result<()> { .collect(); if files.len() == 0 { - bail!("No .jpg files found in current directory"); + error_chain::bail!("No .jpg files found in current directory"); } let thumb_dir = "thumbnails"; diff --git a/src/concurrency/thread/crossbeam-spawn.md b/src/concurrency/thread/crossbeam-spawn.md index 81474f1..65ce6c9 100644 --- a/src/concurrency/thread/crossbeam-spawn.md +++ b/src/concurrency/thread/crossbeam-spawn.md @@ -9,9 +9,7 @@ you can reference data from the calling function. This example splits the array in half and performs the work in separate threads. -```rust -extern crate crossbeam; - +```rust,edition2018 fn main() { let arr = &[1, 25, -4, 10]; let max = find_max(arr); diff --git a/src/concurrency/thread/crossbeam-spsc.md b/src/concurrency/thread/crossbeam-spsc.md index c46ec0a..c989986 100644 --- a/src/concurrency/thread/crossbeam-spsc.md +++ b/src/concurrency/thread/crossbeam-spsc.md @@ -9,9 +9,7 @@ exchanged between the two threads using a [`crossbeam_channel::unbounded`] channel, meaning there is no limit to the number of storeable messages. The producer thread sleeps for half a second in between messages. -```rust -extern crate crossbeam; -extern crate crossbeam_channel; +```rust,edition2018 use std::{thread, time}; use crossbeam_channel::unbounded; diff --git a/src/concurrency/thread/global-mut-state.md b/src/concurrency/thread/global-mut-state.md index cade7cd..91a149b 100644 --- a/src/concurrency/thread/global-mut-state.md +++ b/src/concurrency/thread/global-mut-state.md @@ -9,12 +9,9 @@ the state cannot be simultaneously accessed by multiple threads, preventing race conditions. A [`MutexGuard`] must be acquired to read or mutate the value stored in a [`Mutex`]. -```rust -# #[macro_use] -# extern crate error_chain; -#[macro_use] -extern crate lazy_static; - +```rust,edition2018 +# use error_chain::error_chain; +use lazy_static::lazy_static; use std::sync::Mutex; # # error_chain!{ } diff --git a/src/concurrency/thread/threadpool-fractal.md b/src/concurrency/thread/threadpool-fractal.md index a40e9fc..3bb893d 100644 --- a/src/concurrency/thread/threadpool-fractal.md +++ b/src/concurrency/thread/threadpool-fractal.md @@ -16,14 +16,8 @@ Create [`ThreadPool`] with thread count equal to number of cores with [`num_cpus [`ImageBuffer::put_pixel`] uses the data to set the pixel color. [`ImageBuffer::save`] writes the image to `output.png`. -```rust,no_run -# #[macro_use] -# extern crate error_chain; -extern crate threadpool; -extern crate num; -extern crate num_cpus; -extern crate image; - +```rust,edition2018,no_run +# use error_chain::error_chain; use std::sync::mpsc::{channel, RecvError}; use threadpool::ThreadPool; use num::complex::Complex; diff --git a/src/concurrency/thread/threadpool-walk.md b/src/concurrency/thread/threadpool-walk.md index e664928..5f8559a 100644 --- a/src/concurrency/thread/threadpool-walk.md +++ b/src/concurrency/thread/threadpool-walk.md @@ -8,11 +8,7 @@ present in the system found with [`num_cpus::get`]. [`Walkdir::new`] iterates the current directory and calls [`execute`] to perform the operations of reading and computing SHA256 hash. -```rust,no_run -extern crate walkdir; -extern crate ring; -extern crate num_cpus; -extern crate threadpool; +```rust,edition2018,no_run use walkdir::WalkDir; use std::fs::File; diff --git a/src/cryptography/encryption/pbkdf2.md b/src/cryptography/encryption/pbkdf2.md index cccee35..593d74b 100644 --- a/src/cryptography/encryption/pbkdf2.md +++ b/src/cryptography/encryption/pbkdf2.md @@ -9,9 +9,7 @@ function [`pbkdf2::derive`]. Verifies the hash is correct with [`SecureRandom::fill`], which fills the salt byte array with securely generated random numbers. -```rust,ignore -extern crate ring; -extern crate data_encoding; +```rust,edition2018,ignore use data_encoding::HEXUPPER; use ring::error::Unspecified; diff --git a/src/cryptography/hashing/hmac.md b/src/cryptography/hashing/hmac.md index 2170f98..704d891 100644 --- a/src/cryptography/hashing/hmac.md +++ b/src/cryptography/hashing/hmac.md @@ -4,9 +4,8 @@ Uses [`ring::hmac`] to creates a [`hmac::Signature`] of a string then verifies the signature is correct. -```rust -extern crate ring; +```rust,edition2018 use ring::{hmac, rand}; use ring::rand::SecureRandom; use ring::error::Unspecified; diff --git a/src/cryptography/hashing/sha-digest.md b/src/cryptography/hashing/sha-digest.md index 906c24b..14fca97 100644 --- a/src/cryptography/hashing/sha-digest.md +++ b/src/cryptography/hashing/sha-digest.md @@ -5,12 +5,8 @@ Writes some data to a file, then calculates the SHA-256 [`digest::Digest`] of the file's contents using [`digest::Context`]. -```rust -# #[macro_use] -# extern crate error_chain; -extern crate data_encoding; -extern crate ring; - +```rust,edition2018 +# use error_chain::error_chain; use data_encoding::HEXUPPER; use ring::digest::{Context, Digest, SHA256}; use std::fs::File; diff --git a/src/data_structures/bitfield/bitfield.md b/src/data_structures/bitfield/bitfield.md index 68d325b..4c62a7d 100644 --- a/src/data_structures/bitfield/bitfield.md +++ b/src/data_structures/bitfield/bitfield.md @@ -6,10 +6,8 @@ Creates type safe bitfield type `MyFlags` with help of [`bitflags!`] macro and implements elementary `clear` operation as well as [`Display`] trait for it. Subsequently, shows basic bitwise operations and formatting. -```rust -#[macro_use] -extern crate bitflags; - +```rust,edition2018 +use bitflags::bitflags; use std::fmt; bitflags! { diff --git a/src/database/postgres/aggregate_data.md b/src/database/postgres/aggregate_data.md index 1168732..9667dd3 100644 --- a/src/database/postgres/aggregate_data.md +++ b/src/database/postgres/aggregate_data.md @@ -4,8 +4,7 @@ This recipe lists the nationalities of the first 7999 artists in the database of the [`Museum of Modern Art`] in descending order. -```rust,no_run -extern crate postgres; +```rust,edition2018,no_run use postgres::{Client, Error, NoTls}; struct Nation { diff --git a/src/database/postgres/create_tables.md b/src/database/postgres/create_tables.md index 72ca745..393fdd8 100644 --- a/src/database/postgres/create_tables.md +++ b/src/database/postgres/create_tables.md @@ -6,9 +6,7 @@ Use the [`postgres`] crate to create tables in a Postgres database. [`Client::connect`] helps in connecting to an existing database. The recipe uses a URL string format with `Client::connect`. It assumes an existing database named `library`, the username is `postgres` and the password is `postgres`. -```rust,no_run -extern crate postgres; - +```rust,edition2018,no_run use postgres::{Client, NoTls, Error}; fn main() -> Result<(), Error> { diff --git a/src/database/postgres/insert_query_data.md b/src/database/postgres/insert_query_data.md index cc4e7d4..da1e320 100644 --- a/src/database/postgres/insert_query_data.md +++ b/src/database/postgres/insert_query_data.md @@ -4,9 +4,8 @@ The recipe inserts data into the `author` table using [`execute`] method of `Client`. Then, displays the data from the `author` table using [`query`] method of `Client`. -```rust,no_run -extern crate postgres; +```rust,edition2018,no_run use postgres::{Client, NoTls, Error}; use std::collections::HashMap; diff --git a/src/database/sqlite/initialization.md b/src/database/sqlite/initialization.md index ede5731..a27c536 100644 --- a/src/database/sqlite/initialization.md +++ b/src/database/sqlite/initialization.md @@ -7,9 +7,7 @@ Use the `rusqlite` crate to open SQLite databases. See [`Connection::open`] will create the database if it doesn't already exist. -```rust,no_run -extern crate rusqlite; - +```rust,edition2018,no_run use rusqlite::{Connection, Result}; use rusqlite::NO_PARAMS; diff --git a/src/database/sqlite/insert_select.md b/src/database/sqlite/insert_select.md index 3c6aebc..a1d4bb1 100644 --- a/src/database/sqlite/insert_select.md +++ b/src/database/sqlite/insert_select.md @@ -6,7 +6,6 @@ This recipe inserts data into `cat_colors` and `cats` tables using the [`execute`] method of `Connection`. First, the data is inserted into the `cat_colors` table. After a record for a color is inserted, [`last_insert_rowid`] method of `Connection` is used to get `id` of the last color inserted. This `id` is used while inserting data into the `cats` table. Then, the select query is prepared using the [`prepare`] method which gives a [`statement`] struct. Then, query is executed using [`query_map`] method of [`statement`]. ```rust,no_run -extern crate rusqlite; use rusqlite::NO_PARAMS; use rusqlite::{Connection, Result}; diff --git a/src/database/sqlite/transactions.md b/src/database/sqlite/transactions.md index 22e53af..6eb1605 100644 --- a/src/database/sqlite/transactions.md +++ b/src/database/sqlite/transactions.md @@ -12,9 +12,7 @@ a unique constraint on the color name. When an attempt to insert a duplicate color is made, the transaction rolls back. -```rust,no_run -extern crate rusqlite; - +```rust,edition2018,no_run use rusqlite::{Connection, Result, NO_PARAMS}; fn main() -> Result<()> { diff --git a/src/datetime/duration/checked.md b/src/datetime/duration/checked.md index 4a4042f..2e78a8c 100644 --- a/src/datetime/duration/checked.md +++ b/src/datetime/duration/checked.md @@ -10,8 +10,7 @@ cannot be calculated. Escape sequences that are available for the [`DateTime::format`] can be found at [`chrono::format::strftime`]. -```rust -extern crate chrono; +```rust,edition2018 use chrono::{DateTime, Duration, Utc}; fn day_earlier(date_time: DateTime) -> Option> { diff --git a/src/datetime/duration/profile.md b/src/datetime/duration/profile.md index 03312eb..4b870e7 100644 --- a/src/datetime/duration/profile.md +++ b/src/datetime/duration/profile.md @@ -7,7 +7,7 @@ Measures [`time::Instant::elapsed`] since [`time::Instant::now`]. Calling [`time::Instant::elapsed`] returns a [`time::Duration`] that we print at the end of the example. This method will not mutate or reset the [`time::Instant`] object. -```rust +```rust,edition2018 use std::time::{Duration, Instant}; # use std::thread; # diff --git a/src/datetime/duration/timezone.md b/src/datetime/duration/timezone.md index f194edf..58387c6 100644 --- a/src/datetime/duration/timezone.md +++ b/src/datetime/duration/timezone.md @@ -4,8 +4,7 @@ Gets the local time and displays it using [`offset::Local::now`] and then converts it to the UTC standard using the [`DateTime::from_utc`] struct method. A time is then converted using the [`offset::FixedOffset`] struct and the UTC time is then converted to UTC+8 and UTC-2. -```rust -extern crate chrono; +```rust,edition2018 use chrono::{DateTime, FixedOffset, Local, Utc}; diff --git a/src/datetime/parse/current.md b/src/datetime/parse/current.md index 4573feb..cca5cd5 100644 --- a/src/datetime/parse/current.md +++ b/src/datetime/parse/current.md @@ -5,8 +5,7 @@ Gets the current UTC [`DateTime`] and its hour/minute/second via [`Timelike`] and its year/month/day/weekday via [`Datelike`]. -```rust -extern crate chrono; +```rust,edition2018 use chrono::{Datelike, Timelike, Utc}; fn main() { diff --git a/src/datetime/parse/format.md b/src/datetime/parse/format.md index bf8b655..4366b32 100644 --- a/src/datetime/parse/format.md +++ b/src/datetime/parse/format.md @@ -7,8 +7,7 @@ current time in the well-known formats [RFC 2822] using [`DateTime::to_rfc2822`] and [RFC 3339] using [`DateTime::to_rfc3339`], and in a custom format using [`DateTime::format`]. -```rust -extern crate chrono; +```rust,edition2018 use chrono::{DateTime, Utc}; fn main() { diff --git a/src/datetime/parse/string.md b/src/datetime/parse/string.md index 255715f..a7e898a 100644 --- a/src/datetime/parse/string.md +++ b/src/datetime/parse/string.md @@ -13,8 +13,7 @@ requires that such a DateTime struct must be creatable that it uniquely identifies a date and a time. For parsing dates and times without timezones use [`NaiveDate`], [`NaiveTime`], and [`NaiveDateTime`]. -```rust -extern crate chrono; +```rust,edition2018 use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime}; use chrono::format::ParseError; diff --git a/src/datetime/parse/timestamp.md b/src/datetime/parse/timestamp.md index d94fd0a..3dcc882 100644 --- a/src/datetime/parse/timestamp.md +++ b/src/datetime/parse/timestamp.md @@ -6,8 +6,7 @@ to [UNIX timestamp] using [`NaiveDateTime::timestamp`]. Then it calculates what was the date after one billion seconds since January 1, 1970 0:00:00 UTC, using [`NaiveDateTime::from_timestamp`]. -```rust -extern crate chrono; +```rust,edition2018 use chrono::{NaiveDate, NaiveDateTime}; diff --git a/src/development_tools/build_tools/cc-bundled-cpp.md b/src/development_tools/build_tools/cc-bundled-cpp.md index 3d35e1b..6941395 100644 --- a/src/development_tools/build_tools/cc-bundled-cpp.md +++ b/src/development_tools/build_tools/cc-bundled-cpp.md @@ -18,9 +18,7 @@ cc = "1" ### `build.rs` -```rust,no_run -extern crate cc; - +```rust,edition2018,no_run fn main() { cc::Build::new() .cpp(true) @@ -43,7 +41,7 @@ int multiply(int x, int y) { ### `src/main.rs` -```rust,ignore +```rust,edition2018,ignore extern { fn multiply(x : i32, y : i32) -> i32; } diff --git a/src/development_tools/build_tools/cc-bundled-static.md b/src/development_tools/build_tools/cc-bundled-static.md index 4790082..69f57c2 100644 --- a/src/development_tools/build_tools/cc-bundled-static.md +++ b/src/development_tools/build_tools/cc-bundled-static.md @@ -30,9 +30,7 @@ error-chain = "0.11" ### `build.rs` -```rust,no_run -extern crate cc; - +```rust,edition2018,no_run fn main() { cc::Build::new() .file("src/hello.c") @@ -57,8 +55,7 @@ void greet(const char* name) { ### `src/main.rs` -```rust,ignore -# #[macro_use] extern crate error_chain; +```rust,edition2018,ignore use std::ffi::CString; use std::os::raw::c_char; # diff --git a/src/development_tools/build_tools/cc-defines.md b/src/development_tools/build_tools/cc-defines.md index 19f8d0f..0ce9f04 100644 --- a/src/development_tools/build_tools/cc-defines.md +++ b/src/development_tools/build_tools/cc-defines.md @@ -23,9 +23,7 @@ cc = "1" ### `build.rs` -```rust,no_run -extern crate cc; - +```rust,edition2018,no_run fn main() { cc::Build::new() .define("APP_NAME", "\"foo\"") @@ -51,7 +49,7 @@ void print_app_info() { ### `src/main.rs` -```rust,ignore +```rust,edition2018,ignore extern { fn print_app_info(); } diff --git a/src/development_tools/debugging/config_log/log-custom.md b/src/development_tools/debugging/config_log/log-custom.md index 12aea8b..1bf7b64 100644 --- a/src/development_tools/debugging/config_log/log-custom.md +++ b/src/development_tools/debugging/config_log/log-custom.md @@ -11,12 +11,8 @@ encoding using a custom pattern from [`log4rs::encode::pattern`]. Assigns the configuration to [`log4rs::config::Config`] and sets the default [`log::LevelFilter`]. -```rust,no_run -# #[macro_use] -# extern crate error_chain; -#[macro_use] -extern crate log; -extern crate log4rs; +```rust,edition2018,no_run +# use error_chain::error_chain; use log::LevelFilter; use log4rs::append::file::FileAppender; @@ -44,7 +40,7 @@ fn main() -> Result<()> { log4rs::init_config(config)?; - info!("Hello, world!"); + log::info!("Hello, world!"); Ok(()) } diff --git a/src/development_tools/debugging/config_log/log-env-variable.md b/src/development_tools/debugging/config_log/log-env-variable.md index 8e5f9bc..1c946c3 100644 --- a/src/development_tools/debugging/config_log/log-env-variable.md +++ b/src/development_tools/debugging/config_log/log-env-variable.md @@ -9,10 +9,7 @@ environment variable contents in the form of [`RUST_LOG`] syntax. Then, [`Builder::init`] initializes the logger. All these steps are normally done internally by [`env_logger::init`]. -```rust -#[macro_use] -extern crate log; -extern crate env_logger; +```rust,edition2018 use std::env; use env_logger::Builder; @@ -22,9 +19,9 @@ fn main() { .parse(&env::var("MY_APP_LOG").unwrap_or_default()) .init(); - info!("informational message"); - warn!("warning message"); - error!("this is an error {}", "message"); + log::info!("informational message"); + log::warn!("warning message"); + log::error!("this is an error {}", "message"); } ``` diff --git a/src/development_tools/debugging/config_log/log-mod.md b/src/development_tools/debugging/config_log/log-mod.md index c5a6775..87bd659 100644 --- a/src/development_tools/debugging/config_log/log-mod.md +++ b/src/development_tools/debugging/config_log/log-mod.md @@ -5,33 +5,30 @@ Creates two modules `foo` and nested `foo::bar` with logging directives controlled separately with [`RUST_LOG`] environmental variable. -```rust -#[macro_use] -extern crate log; -extern crate env_logger; +```rust,edition2018 mod foo { mod bar { pub fn run() { - warn!("[bar] warn"); - info!("[bar] info"); - debug!("[bar] debug"); + log::warn!("[bar] warn"); + log::info!("[bar] info"); + log::debug!("[bar] debug"); } } pub fn run() { - warn!("[foo] warn"); - info!("[foo] info"); - debug!("[foo] debug"); + log::warn!("[foo] warn"); + log::info!("[foo] info"); + log::debug!("[foo] debug"); bar::run(); } } fn main() { env_logger::init(); - warn!("[root] warn"); - info!("[root] info"); - debug!("[root] debug"); + log::warn!("[root] warn"); + log::info!("[root] info"); + log::debug!("[root] debug"); foo::run(); } ``` diff --git a/src/development_tools/debugging/config_log/log-timestamp.md b/src/development_tools/debugging/config_log/log-timestamp.md index 0ff8731..1752a60 100644 --- a/src/development_tools/debugging/config_log/log-timestamp.md +++ b/src/development_tools/debugging/config_log/log-timestamp.md @@ -10,12 +10,7 @@ a timestamp used in the final log. The example calls [`Builder::format`] to set a closure which formats each message text with timestamp, [`Record::level`] and body ([`Record::args`]). -```rust -#[macro_use] -extern crate log; -extern crate chrono; -extern crate env_logger; - +```rust,edition2018 use std::io::Write; use chrono::Local; use env_logger::Builder; @@ -34,9 +29,9 @@ fn main() { .filter(None, LevelFilter::Info) .init(); - warn!("warn"); - info!("info"); - debug!("debug"); + log::warn!("warn"); + log::info!("info"); + log::debug!("debug"); } ``` stderr output will contain diff --git a/src/development_tools/debugging/log/log-custom-logger.md b/src/development_tools/debugging/log/log-custom-logger.md index 4449774..403fd49 100644 --- a/src/development_tools/debugging/log/log-custom-logger.md +++ b/src/development_tools/debugging/log/log-custom-logger.md @@ -6,10 +6,7 @@ Implements a custom logger `ConsoleLogger` which prints to stdout. In order to use the logging macros, `ConsoleLogger` implements the [`log::Log`] trait and [`log::set_logger`] installs it. -```rust -#[macro_use] -extern crate log; - +```rust,edition2018 use log::{Record, Level, Metadata, LevelFilter, SetLoggerError}; static CONSOLE_LOGGER: ConsoleLogger = ConsoleLogger; @@ -34,9 +31,9 @@ fn main() -> Result<(), SetLoggerError> { log::set_logger(&CONSOLE_LOGGER)?; log::set_max_level(LevelFilter::Info); - info!("hello log"); - warn!("warning"); - error!("oops"); + log::info!("hello log"); + log::warn!("warning"); + log::error!("oops"); Ok(()) } ``` diff --git a/src/development_tools/debugging/log/log-debug.md b/src/development_tools/debugging/log/log-debug.md index 2ab725e..28e0a2e 100644 --- a/src/development_tools/debugging/log/log-debug.md +++ b/src/development_tools/debugging/log/log-debug.md @@ -3,16 +3,13 @@ [![log-badge]][log] [![env_logger-badge]][env_logger] [![cat-debugging-badge]][cat-debugging] The `log` crate provides logging utilities. The `env_logger` crate configures -logging via an environment variable. The [`debug!`] macro works like other +logging via an environment variable. The [`log::debug!`] macro works like other [`std::fmt`] formatted strings. -```rust -#[macro_use] -extern crate log; -extern crate env_logger; +```rust,edition2018 fn execute_query(query: &str) { - debug!("Executing query: {}", query); + log::debug!("Executing query: {}", query); } fn main() { @@ -38,5 +35,5 @@ following line at the very end of the output: DEBUG:main: Executing query: DROP TABLE students ``` -[`debug!`]: https://docs.rs/log/*/log/macro.debug.html +[`log::debug!`]: https://docs.rs/log/*/log/macro.debug.html [`std::fmt`]: https://doc.rust-lang.org/std/fmt/ diff --git a/src/development_tools/debugging/log/log-error.md b/src/development_tools/debugging/log/log-error.md index 52dd923..a30c1f4 100644 --- a/src/development_tools/debugging/log/log-error.md +++ b/src/development_tools/debugging/log/log-error.md @@ -3,12 +3,9 @@ [![log-badge]][log] [![env_logger-badge]][env_logger] [![cat-debugging-badge]][cat-debugging] Proper error handling considers exceptions exceptional. Here, an error logs -to stderr with `log`'s convenience macro [`error!`]. +to stderr with `log`'s convenience macro [`log::error!`]. -```rust -#[macro_use] -extern crate log; -extern crate env_logger; +```rust,edition2018 fn execute_query(_query: &str) -> Result<(), &'static str> { Err("I'm afraid I can't do that") @@ -19,9 +16,9 @@ fn main() { let response = execute_query("DROP TABLE students"); if let Err(err) = response { - error!("Failed to execute query: {}", err); + log::error!("Failed to execute query: {}", err); } } ``` -[`error!`]: https://docs.rs/log/*/log/macro.error.html +[`log::error!`]: https://docs.rs/log/*/log/macro.error.html diff --git a/src/development_tools/debugging/log/log-stdout.md b/src/development_tools/debugging/log/log-stdout.md index 112082a..9203d38 100644 --- a/src/development_tools/debugging/log/log-stdout.md +++ b/src/development_tools/debugging/log/log-stdout.md @@ -4,10 +4,7 @@ Creates a custom logger configuration using the [`Builder::target`] to set the target of the log output to [`Target::Stdout`]. -```rust -#[macro_use] -extern crate log; -extern crate env_logger; +```rust,edition2018 use env_logger::{Builder, Target}; @@ -16,7 +13,7 @@ fn main() { .target(Target::Stdout) .init(); - error!("This error has been printed to Stdout"); + log::error!("This error has been printed to Stdout"); } ``` diff --git a/src/development_tools/debugging/log/log-syslog.md b/src/development_tools/debugging/log/log-syslog.md index 8ec32d8..39e4308 100644 --- a/src/development_tools/debugging/log/log-syslog.md +++ b/src/development_tools/debugging/log/log-syslog.md @@ -7,12 +7,8 @@ with [`syslog::init`]. [`syslog::Facility`] records the program submitting the log entry's classification, [`log::LevelFilter`] denotes allowed log verbosity and `Option<&str>` holds optional application name. -```rust -#[macro_use] -extern crate log; +```rust,edition2018 # #[cfg(target_os = "linux")] -extern crate syslog; - # #[cfg(target_os = "linux")] use syslog::{Facility, Error}; @@ -21,8 +17,8 @@ fn main() -> Result<(), Error> { syslog::init(Facility::LOG_USER, log::LevelFilter::Debug, Some("My app name"))?; - debug!("this is a debug {}", "message"); - error!("this is an error!"); + log::debug!("this is a debug {}", "message"); + log::error!("this is an error!"); Ok(()) } diff --git a/src/development_tools/versioning/semver-command.md b/src/development_tools/versioning/semver-command.md index f0b7fb3..c5c5274 100644 --- a/src/development_tools/versioning/semver-command.md +++ b/src/development_tools/versioning/semver-command.md @@ -7,10 +7,8 @@ Runs `git --version` using [`Command`], then parses the version number into a [`semver::VersionReq`] to the parsed version. The command output resembles "git version x.y.z". -```rust,no_run -# #[macro_use] -# extern crate error_chain; -extern crate semver; +```rust,edition2018,no_run +# use error_chain::error_chain; use std::process::Command; use semver::{Version, VersionReq}; @@ -30,7 +28,7 @@ fn main() -> Result<()> { let output = Command::new("git").arg("--version").output()?; if !output.status.success() { - bail!("Command executed with failing error code"); + error_chain::bail!("Command executed with failing error code"); } let stdout = String::from_utf8(output.stdout)?; @@ -40,7 +38,7 @@ fn main() -> Result<()> { let parsed_version = Version::parse(version)?; if !version_test.matches(&parsed_version) { - bail!("Command version lower than minimum supported version (found {}, need {})", + error_chain::bail!("Command version lower than minimum supported version (found {}, need {})", parsed_version, version_constraint); } diff --git a/src/development_tools/versioning/semver-complex.md b/src/development_tools/versioning/semver-complex.md index 0b6ede2..5903a37 100644 --- a/src/development_tools/versioning/semver-complex.md +++ b/src/development_tools/versioning/semver-complex.md @@ -8,9 +8,7 @@ contains pre-release and build metadata as defined in the [Semantic Versioning S Note that, in accordance with the Specification, build metadata is parsed but not considered when comparing versions. In other words, two versions may be equal even if their build strings differ. -```rust -extern crate semver; - +```rust,edition2018 use semver::{Identifier, Version, SemVerError}; fn main() -> Result<(), SemVerError> { diff --git a/src/development_tools/versioning/semver-increment.md b/src/development_tools/versioning/semver-increment.md index 02b1fd8..de4f7f0 100644 --- a/src/development_tools/versioning/semver-increment.md +++ b/src/development_tools/versioning/semver-increment.md @@ -10,9 +10,7 @@ incrementing the minor version number resets the patch version number to 0 and incrementing the major version number resets both the minor and patch version numbers to 0. -```rust -extern crate semver; - +```rust,edition2018 use semver::{Version, SemVerError}; fn main() -> Result<(), SemVerError> { diff --git a/src/development_tools/versioning/semver-latest.md b/src/development_tools/versioning/semver-latest.md index bd70cb1..daab5ee 100644 --- a/src/development_tools/versioning/semver-latest.md +++ b/src/development_tools/versioning/semver-latest.md @@ -6,10 +6,8 @@ Given a list of version &strs, finds the latest [`semver::Version`]. [`semver::VersionReq`] filters the list with [`VersionReq::matches`]. Also demonstrates `semver` pre-release preferences. -```rust -# #[macro_use] -# extern crate error_chain; -extern crate semver; +```rust,edition2018 +# use error_chain::error_chain; use semver::{Version, VersionReq}; # diff --git a/src/development_tools/versioning/semver-prerelease.md b/src/development_tools/versioning/semver-prerelease.md index e83cbea..d5289e0 100644 --- a/src/development_tools/versioning/semver-prerelease.md +++ b/src/development_tools/versioning/semver-prerelease.md @@ -4,9 +4,7 @@ Given two versions, [`is_prerelease`] asserts that one is pre-release and the other is not. -```rust -extern crate semver; - +```rust,edition2018 use semver::{Version, SemVerError}; fn main() -> Result<(), SemVerError> { diff --git a/src/encoding/complex/endian-byte.md b/src/encoding/complex/endian-byte.md index ac34eca..7fd8adc 100644 --- a/src/encoding/complex/endian-byte.md +++ b/src/encoding/complex/endian-byte.md @@ -6,8 +6,7 @@ be necessary when receiving information over the network, such that bytes received are from another system. -```rust -extern crate byteorder; +```rust,edition2018 use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use std::io::Error; diff --git a/src/encoding/complex/json.md b/src/encoding/complex/json.md index c4ab696..dda1e2c 100644 --- a/src/encoding/complex/json.md +++ b/src/encoding/complex/json.md @@ -10,10 +10,8 @@ is able to represent any valid JSON data. The example below shows a `&str` of JSON being parsed. The expected value is declared using the [`json!`] macro. -```rust -#[macro_use] -extern crate serde_json; - +```rust,edition2018 + use serde_json::json; use serde_json::{Value, Error}; fn main() -> Result<(), Error> { diff --git a/src/encoding/complex/toml.md b/src/encoding/complex/toml.md index 4f0de96..7cca2a0 100644 --- a/src/encoding/complex/toml.md +++ b/src/encoding/complex/toml.md @@ -5,9 +5,7 @@ Parse some TOML into a universal `toml::Value` that is able to represent any valid TOML data. -```rust -extern crate toml; - +```rust,edition2018 use toml::{Value, de::Error}; fn main() -> Result<(), Error> { @@ -33,10 +31,8 @@ fn main() -> Result<(), Error> { Parse TOML into your own structs using [Serde]. -```rust -#[macro_use] -extern crate serde_derive; -extern crate toml; +```rust,edition2018 +use serde::Deserialize; use toml::de::Error; use std::collections::HashMap; diff --git a/src/encoding/csv/delimiter.md b/src/encoding/csv/delimiter.md index 643c391..50d2128 100644 --- a/src/encoding/csv/delimiter.md +++ b/src/encoding/csv/delimiter.md @@ -4,12 +4,9 @@ Reads CSV records with a tab [`delimiter`]. -```rust -extern crate csv; +```rust,edition2018 use csv::Error; -#[macro_use] -extern crate serde_derive; - +use serde::Deserialize; #[derive(Debug, Deserialize)] struct Record { name: String, diff --git a/src/encoding/csv/filter.md b/src/encoding/csv/filter.md index c34e9e3..9999641 100644 --- a/src/encoding/csv/filter.md +++ b/src/encoding/csv/filter.md @@ -4,10 +4,8 @@ Returns _only_ the rows from `data` with a field that matches `query`. -```rust -# #[macro_use] -# extern crate error_chain; -extern crate csv; +```rust,edition2018 +# use error_chain::error_chain; use std::io; # diff --git a/src/encoding/csv/invalid.md b/src/encoding/csv/invalid.md index 9461cf7..086371b 100644 --- a/src/encoding/csv/invalid.md +++ b/src/encoding/csv/invalid.md @@ -6,11 +6,9 @@ CSV files often contain invalid data. For these cases, the `csv` crate provides a custom deserializer, [`csv::invalid_option`], which automatically converts invalid data to None values. -```rust -extern crate csv; +```rust,edition2018 use csv::Error; -#[macro_use] -extern crate serde_derive; +use serde::Deserialize; #[derive(Debug, Deserialize)] struct Record { diff --git a/src/encoding/csv/read.md b/src/encoding/csv/read.md index 3820e79..055e860 100644 --- a/src/encoding/csv/read.md +++ b/src/encoding/csv/read.md @@ -6,8 +6,7 @@ Reads standard CSV records into [`csv::StringRecord`] — a weakly typed data representation which expects valid UTF-8 rows. Alternatively, [`csv::ByteRecord`] makes no assumptions about UTF-8. -```rust -extern crate csv; +```rust,edition2018 use csv::Error; fn main() -> Result<(), Error> { @@ -34,11 +33,8 @@ fn main() -> Result<(), Error> { Serde deserializes data into strongly type structures. See the [`csv::Reader::deserialize`] method. -```rust -extern crate csv; -#[macro_use] -extern crate serde_derive; - +```rust,edition2018 +use serde::Deserialize; #[derive(Deserialize)] struct Record { year: u16, diff --git a/src/encoding/csv/serde-serialize.md b/src/encoding/csv/serde-serialize.md index 56bcce3..cbbf08d 100644 --- a/src/encoding/csv/serde-serialize.md +++ b/src/encoding/csv/serde-serialize.md @@ -5,13 +5,9 @@ The following example shows how to serialize custom structs as CSV records using the [serde] crate. -```rust -# #[macro_use] -# extern crate error_chain; -extern crate csv; -#[macro_use] -extern crate serde_derive; - +```rust,edition2018 +# use error_chain::error_chain; +use serde::Serialize; use std::io; # # error_chain! { diff --git a/src/encoding/csv/serialize.md b/src/encoding/csv/serialize.md index d0ae675..bc9ffb1 100644 --- a/src/encoding/csv/serialize.md +++ b/src/encoding/csv/serialize.md @@ -8,10 +8,8 @@ a simple record containing string data only. Data with more complex values such as numbers, floats, and options use [`serialize`]. Since CSV writer uses internal buffer, always explicitly [`flush`] when done. -```rust -# #[macro_use] -# extern crate error_chain; -extern crate csv; +```rust,edition2018 +# use error_chain::error_chain; use std::io; # diff --git a/src/encoding/csv/transform.md b/src/encoding/csv/transform.md index a0c10fc..2b1a261 100644 --- a/src/encoding/csv/transform.md +++ b/src/encoding/csv/transform.md @@ -8,14 +8,8 @@ csv file, and [serde] to deserialize and serialize the rows to and from bytes. See [`csv::Reader::deserialize`], [`serde::Deserialize`], and [`std::str::FromStr`] -```rust -extern crate csv; -# #[macro_use] -# extern crate error_chain; -#[macro_use] -extern crate serde_derive; -extern crate serde; - +```rust,edition2018 +# use error_chain::error_chain; use csv::{Reader, Writer}; use serde::{de, Deserialize, Deserializer}; use std::str::FromStr; diff --git a/src/encoding/string/base64.md b/src/encoding/string/base64.md index 899af27..d8a808b 100644 --- a/src/encoding/string/base64.md +++ b/src/encoding/string/base64.md @@ -5,10 +5,8 @@ Encodes byte slice into `base64` String using [`encode`] and decodes it with [`decode`]. -```rust -# #[macro_use] -# extern crate error_chain; -extern crate base64; +```rust,edition2018 +# use error_chain::error_chain; use std::str; use base64::{encode, decode}; diff --git a/src/encoding/string/hex.md b/src/encoding/string/hex.md index 63978e1..3cd2914 100644 --- a/src/encoding/string/hex.md +++ b/src/encoding/string/hex.md @@ -12,9 +12,7 @@ returns a `Vec` if the input data is successfully decoded. The example below coverts `&[u8]` data to hexadecimal equivalent. Compares this value to the expected value. -```rust -extern crate data_encoding; - +```rust,edition2018 use data_encoding::{HEXUPPER, DecodeError}; fn main() -> Result<(), DecodeError> { diff --git a/src/encoding/string/percent-encode.md b/src/encoding/string/percent-encode.md index 8a35901..9d37a39 100644 --- a/src/encoding/string/percent-encode.md +++ b/src/encoding/string/percent-encode.md @@ -6,9 +6,7 @@ Encode an input string with [percent-encoding] using the [`utf8_percent_encode`] function from the `percent-encoding` crate. Then decode using the [`percent_decode`] function. -```rust,ignore -extern crate percent_encoding; - +```rust,edition2018,ignore use percent_encoding::{utf8_percent_encode, percent_decode, AsciiSet, CONTROLS}; use std::str::Utf8Error; diff --git a/src/encoding/string/url-encode.md b/src/encoding/string/url-encode.md index 94bd527..c907e12 100644 --- a/src/encoding/string/url-encode.md +++ b/src/encoding/string/url-encode.md @@ -7,8 +7,7 @@ using the [`form_urlencoded::byte_serialize`] and subsequently decodes it with [`form_urlencoded::parse`]. Both functions return iterators that collect into a `String`. -```rust -extern crate url; +```rust,edition2018 use url::form_urlencoded::{byte_serialize, parse}; fn main() { diff --git a/src/errors/handle/backtrace.md b/src/errors/handle/backtrace.md index 07334bd..e1e9eb2 100644 --- a/src/errors/handle/backtrace.md +++ b/src/errors/handle/backtrace.md @@ -11,12 +11,9 @@ The below recipes attempts to deserialize the value `256` into a `u8`. An error will bubble up from Serde then csv and finally up to the user code. -```rust -# extern crate csv; -#[macro_use] -extern crate error_chain; -# #[macro_use] -# extern crate serde_derive; +```rust,edition2018 +use error_chain::error_chain; +# use serde::Deserialize; # # use std::fmt; # diff --git a/src/errors/handle/main.md b/src/errors/handle/main.md index d7387a3..de72750 100644 --- a/src/errors/handle/main.md +++ b/src/errors/handle/main.md @@ -17,9 +17,8 @@ first number. Returns uptime unless there is an error. Other recipes in this book will hide the [error-chain] boilerplate, and can be seen by expanding the code with the ⤢ button. -```rust -#[macro_use] -extern crate error_chain; +```rust,edition2018 +use error_chain::error_chain; use std::fs::File; use std::io::Read; diff --git a/src/errors/handle/retain.md b/src/errors/handle/retain.md index 6147a43..1ff94c2 100644 --- a/src/errors/handle/retain.md +++ b/src/errors/handle/retain.md @@ -12,10 +12,8 @@ the string response into an integer. The Rust standard library, use [`foreign_links`]. An additional [`ErrorKind`] variant for the web service error uses `errors` block of the `error_chain!` macro. -```rust -#[macro_use] -extern crate error_chain; -extern crate reqwest; +```rust,edition2018 +use error_chain::error_chain; use std::io::Read; diff --git a/src/file/dir/duplicate-name.md b/src/file/dir/duplicate-name.md index e18ac99..d8797b7 100644 --- a/src/file/dir/duplicate-name.md +++ b/src/file/dir/duplicate-name.md @@ -5,9 +5,7 @@ Find recursively in the current directory duplicate filenames, printing them only once. -```rust,no_run -extern crate walkdir; - +```rust,edition2018,no_run use std::collections::HashMap; use walkdir::WalkDir; diff --git a/src/file/dir/find-file.md b/src/file/dir/find-file.md index 528916b..755b26e 100644 --- a/src/file/dir/find-file.md +++ b/src/file/dir/find-file.md @@ -6,10 +6,8 @@ Find JSON files modified within the last day in the current directory. Using [`follow_links`] ensures symbolic links are followed like they were normal directories and files. -```rust,no_run -# #[macro_use] -# extern crate error_chain; -extern crate walkdir; +```rust,edition2018,no_run +# use error_chain::error_chain; use walkdir::WalkDir; # diff --git a/src/file/dir/ignore-case.md b/src/file/dir/ignore-case.md index 74898dc..c62e729 100644 --- a/src/file/dir/ignore-case.md +++ b/src/file/dir/ignore-case.md @@ -6,10 +6,8 @@ Find all image files in the `/media/` directory matching the `img_[0-9]*.png` pa A custom [`MatchOptions`] struct is passed to the [`glob_with`] function making the glob pattern case insensitive while keeping the other options [`Default`]. -```rust,no_run -# #[macro_use] -# extern crate error_chain; -extern crate glob; +```rust,edition2018,no_run +# use error_chain::error_chain; use glob::{glob_with, MatchOptions}; # diff --git a/src/file/dir/loops.md b/src/file/dir/loops.md index 6527543..91d99f6 100644 --- a/src/file/dir/loops.md +++ b/src/file/dir/loops.md @@ -10,9 +10,7 @@ ln -s /tmp/foo/ /tmp/foo/bar/baz/qux ``` The following would assert that a loop exists. -```rust,no_run -extern crate same_file; - +```rust,edition2018,no_run use std::io; use std::path::{Path, PathBuf}; use same_file::is_same_file; diff --git a/src/file/dir/modified.md b/src/file/dir/modified.md index c51fbd8..7299953 100644 --- a/src/file/dir/modified.md +++ b/src/file/dir/modified.md @@ -10,9 +10,8 @@ last modification. [`Duration::as_secs`] converts the time to seconds and compared with 24 hours (24 * 60 * 60 seconds). [`Metadata::is_file`] filters out directories. -```rust -# #[macro_use] -# extern crate error_chain; +```rust,edition2018 +# use error_chain::error_chain; # use std::{env, fs}; diff --git a/src/file/dir/png.md b/src/file/dir/png.md index e2b060d..49169db 100644 --- a/src/file/dir/png.md +++ b/src/file/dir/png.md @@ -8,10 +8,8 @@ In this case, the `**` pattern matches the current directory and all subdirector Use the `**` pattern in any path portion. For example, `/media/**/*.png` matches all PNGs in `media` and it's subdirectories. -```rust,no_run -# #[macro_use] -# extern crate error_chain; -extern crate glob; +```rust,edition2018,no_run +# use error_chain::error_chain; use glob::glob; # diff --git a/src/file/dir/sizes.md b/src/file/dir/sizes.md index a1974df..029aebc 100644 --- a/src/file/dir/sizes.md +++ b/src/file/dir/sizes.md @@ -5,9 +5,7 @@ Recursion depth can be flexibly set by [`WalkDir::min_depth`] & [`WalkDir::max_depth`] methods. Calculates sum of all file sizes to 3 subfolders depth, ignoring files in the root folder. -```rust -extern crate walkdir; - +```rust,edition2018 use walkdir::WalkDir; fn main() { diff --git a/src/file/dir/skip-dot.md b/src/file/dir/skip-dot.md index 760e671..10a5639 100644 --- a/src/file/dir/skip-dot.md +++ b/src/file/dir/skip-dot.md @@ -10,9 +10,7 @@ Uses [`filter_entry`] to descend recursively into entries passing the Root dir `"."` yields through [`WalkDir::depth`] usage in `is_not_hidden` predicate. -```rust,no_run -extern crate walkdir; - +```rust,edition2018,no_run use walkdir::{DirEntry, WalkDir}; fn is_not_hidden(entry: &DirEntry) -> bool { diff --git a/src/file/read-write/memmap.md b/src/file/read-write/memmap.md index dc8edd0..bd349c4 100644 --- a/src/file/read-write/memmap.md +++ b/src/file/read-write/memmap.md @@ -10,9 +10,7 @@ The [`Mmap::map`] function assumes the file behind the memory map is not being modified at the same time by another process or else a [race condition] occurs. -```rust -extern crate memmap; - +```rust,edition2018 use memmap::Mmap; use std::fs::File; use std::io::{Write, Error}; diff --git a/src/file/read-write/read-file.md b/src/file/read-write/read-file.md index fd860c6..8b173fc 100644 --- a/src/file/read-write/read-file.md +++ b/src/file/read-write/read-file.md @@ -8,7 +8,7 @@ time with the [`Lines`] iterator created by trait. [`File::create`] opens a [`File`] for writing, [`File::open`] for reading. -```rust +```rust,edition2018 use std::fs::File; use std::io::{Write, BufReader, BufRead, Error}; diff --git a/src/file/read-write/same-file.md b/src/file/read-write/same-file.md index da96011..2a27551 100644 --- a/src/file/read-write/same-file.md +++ b/src/file/read-write/same-file.md @@ -6,9 +6,7 @@ Use [`same_file::Handle`] to a file that can be tested for equality with other handles. In this example, the handles of file to be read from and to be written to are tested for equality. -```rust,no_run -extern crate same_file; - +```rust,edition2018,no_run use same_file::Handle; use std::fs::File; use std::io::{BufRead, BufReader, Error, ErrorKind}; diff --git a/src/hardware/processor/cpu-count.md b/src/hardware/processor/cpu-count.md index d06063e..b010e35 100644 --- a/src/hardware/processor/cpu-count.md +++ b/src/hardware/processor/cpu-count.md @@ -4,9 +4,7 @@ Shows the number of logical CPU cores in current machine using [`num_cpus::get`]. -```rust -extern crate num_cpus; - +```rust,edition2018 fn main() { println!("Number of logical cores is {}", num_cpus::get()); } diff --git a/src/mem/global_static/lazy-constant.md b/src/mem/global_static/lazy-constant.md index 3de4aa0..fda3ff8 100644 --- a/src/mem/global_static/lazy-constant.md +++ b/src/mem/global_static/lazy-constant.md @@ -5,10 +5,8 @@ Declares a lazily evaluated constant [`HashMap`]. The [`HashMap`] will be evaluated once and stored behind a global static reference. -```rust -#[macro_use] -extern crate lazy_static; - +```rust,edition2018 +use lazy_static::lazy_static; use std::collections::HashMap; lazy_static! { diff --git a/src/net/server/listen-unused.md b/src/net/server/listen-unused.md index ef525cb..4677cb8 100644 --- a/src/net/server/listen-unused.md +++ b/src/net/server/listen-unused.md @@ -6,7 +6,7 @@ In this example, the port is displayed on the console, and the program will listen until a request is made. `SocketAddrV4` assigns a random port when setting port to 0. -```rust,no_run +```rust,edition2018,no_run use std::net::{SocketAddrV4, Ipv4Addr, TcpListener}; use std::io::{Read, Error}; diff --git a/src/os/external/continuous.md b/src/os/external/continuous.md index 693a7b8..6bee1dd 100644 --- a/src/os/external/continuous.md +++ b/src/os/external/continuous.md @@ -10,7 +10,7 @@ The recipe below calls [`Stdio::piped`] to create a pipe, and reads The below recipe is equivalent to the Unix shell command `journalctl | grep usb`. -```rust,no_run +```rust,edition2018,no_run use std::process::{Command, Stdio}; use std::io::{BufRead, BufReader, Error, ErrorKind}; diff --git a/src/os/external/error-file.md b/src/os/external/error-file.md index cf82448..9402ed1 100644 --- a/src/os/external/error-file.md +++ b/src/os/external/error-file.md @@ -12,7 +12,7 @@ cursor position. The below recipe is equivalent to run the Unix shell command `ls . oops >out.txt 2>&1`. -```rust,no_run +```rust,edition2018,no_run use std::fs::File; use std::io::Error; use std::process::{Command, Stdio}; diff --git a/src/os/external/piped.md b/src/os/external/piped.md index 9789bfa..5c65506 100644 --- a/src/os/external/piped.md +++ b/src/os/external/piped.md @@ -9,9 +9,8 @@ sort -hr | head -n 10`. [`Command`]s represent a process. Output of a child process is captured with a [`Stdio::piped`] between parent and child. -```rust,no_run -# #[macro_use] -# extern crate error_chain; +```rust,edition2018,no_run +# use error_chain::error_chain; # use std::process::{Command, Stdio}; # diff --git a/src/os/external/process-output.md b/src/os/external/process-output.md index d60eaff..4f3b958 100644 --- a/src/os/external/process-output.md +++ b/src/os/external/process-output.md @@ -5,10 +5,8 @@ Runs `git log --oneline` as an external [`Command`] and inspects its [`Output`] using [`Regex`] to get the hash and message of the last 5 commits. -```rust,no_run -# #[macro_use] -# extern crate error_chain; -extern crate regex; +```rust,edition2018,no_run +# use error_chain::error_chain; use std::process::Command; use regex::Regex; @@ -31,7 +29,7 @@ fn main() -> Result<()> { let output = Command::new("git").arg("log").arg("--oneline").output()?; if !output.status.success() { - bail!("Command executed with failing error code"); + error_chain::bail!("Command executed with failing error code"); } let pattern = Regex::new(r"(?x) diff --git a/src/os/external/send-input.md b/src/os/external/send-input.md index bd592ee..85a99b7 100644 --- a/src/os/external/send-input.md +++ b/src/os/external/send-input.md @@ -5,9 +5,8 @@ Opens the `python` interpreter using an external [`Command`] and passes it a python statement for execution. [`Output`] of statement is then parsed. -```rust,no_run -# #[macro_use] -# extern crate error_chain; +```rust,edition2018,no_run +# use error_chain::error_chain; # use std::collections::HashSet; use std::io::Write; @@ -44,7 +43,7 @@ fn main() -> Result<()> { Ok(()) } else { let err = String::from_utf8(output.stderr)?; - bail!("External command failed:\n {}", err) + error_chain::bail!("External command failed:\n {}", err) } } ``` diff --git a/src/science/mathematics/complex_numbers/add-complex.md b/src/science/mathematics/complex_numbers/add-complex.md index 7be8455..7dee3e0 100644 --- a/src/science/mathematics/complex_numbers/add-complex.md +++ b/src/science/mathematics/complex_numbers/add-complex.md @@ -6,9 +6,7 @@ Performing mathematical operations on complex numbers is the same as on built in types: the numbers in question must be of the same type (i.e. floats or integers). -```rust -extern crate num; - +```rust,edition2018 fn main() { let complex_num1 = num::complex::Complex::new(10.0, 20.0); // Must use floats let complex_num2 = num::complex::Complex::new(3.1, -4.2); diff --git a/src/science/mathematics/complex_numbers/create-complex.md b/src/science/mathematics/complex_numbers/create-complex.md index 48c4cd1..59cb835 100644 --- a/src/science/mathematics/complex_numbers/create-complex.md +++ b/src/science/mathematics/complex_numbers/create-complex.md @@ -5,9 +5,7 @@ Creates complex numbers of type [`num::complex::Complex`]. Both the real and imaginary part of the complex number must be of the same type. -```rust -extern crate num; - +```rust,edition2018 fn main() { let complex_integer = num::complex::Complex::new(10, 20); let complex_float = num::complex::Complex::new(10.1, 20.1); diff --git a/src/science/mathematics/complex_numbers/mathematical-functions.md b/src/science/mathematics/complex_numbers/mathematical-functions.md index 9a95f50..f6d362d 100644 --- a/src/science/mathematics/complex_numbers/mathematical-functions.md +++ b/src/science/mathematics/complex_numbers/mathematical-functions.md @@ -8,9 +8,7 @@ of sine functions as well as the number e. To use these functions with complex numbers, the Complex type has a few built in functions, all of which can be found here: [`num::complex::Complex`]. -```rust -extern crate num; - +```rust,edition2018 use std::f64::consts::PI; use num::complex::Complex; diff --git a/src/science/mathematics/linear_algebra/add-matrices.md b/src/science/mathematics/linear_algebra/add-matrices.md index f223b68..6adb8e7 100644 --- a/src/science/mathematics/linear_algebra/add-matrices.md +++ b/src/science/mathematics/linear_algebra/add-matrices.md @@ -5,9 +5,7 @@ Creates two 2-D matrices with [`ndarray::arr2`] and sums them element-wise. Note the sum is computed as `let sum = &a + &b`. The `&` operator is used to avoid consuming `a` and `b`, making them available later for display. A new array is created containing their sum. -```rust -extern crate ndarray; - +```rust,edition2018 use ndarray::arr2; fn main() { diff --git a/src/science/mathematics/linear_algebra/invert-matrix.md b/src/science/mathematics/linear_algebra/invert-matrix.md index 96f6cf5..a793eb6 100644 --- a/src/science/mathematics/linear_algebra/invert-matrix.md +++ b/src/science/mathematics/linear_algebra/invert-matrix.md @@ -3,9 +3,7 @@ Creates a 3x3 matrix with [`nalgebra::Matrix3`] and inverts it, if possible. -```rust -extern crate nalgebra; - +```rust,edition2018 use nalgebra::Matrix3; fn main() { diff --git a/src/science/mathematics/linear_algebra/multiply-matrices.md b/src/science/mathematics/linear_algebra/multiply-matrices.md index 01e7795..3eb79ee 100644 --- a/src/science/mathematics/linear_algebra/multiply-matrices.md +++ b/src/science/mathematics/linear_algebra/multiply-matrices.md @@ -3,9 +3,7 @@ Creates two matrices with [`ndarray::arr2`] and performs matrix multiplication on them with [`ndarray::ArrayBase::dot`]. -```rust -extern crate ndarray; - +```rust,edition2018 use ndarray::arr2; fn main() { diff --git a/src/science/mathematics/linear_algebra/multiply-scalar-vector-matrix.md b/src/science/mathematics/linear_algebra/multiply-scalar-vector-matrix.md index 2beed7c..13657d9 100644 --- a/src/science/mathematics/linear_algebra/multiply-scalar-vector-matrix.md +++ b/src/science/mathematics/linear_algebra/multiply-scalar-vector-matrix.md @@ -15,9 +15,7 @@ a 2-D array with one row or one column must be used instead. In this example, the vector is a 1-D array on the right-hand side, so `dot` handles it as a column vector. -```rust -extern crate ndarray; - +```rust,edition2018 use ndarray::{arr1, arr2, Array1}; fn main() { diff --git a/src/science/mathematics/linear_algebra/vector-comparison.md b/src/science/mathematics/linear_algebra/vector-comparison.md index 0078731..e2f05ff 100644 --- a/src/science/mathematics/linear_algebra/vector-comparison.md +++ b/src/science/mathematics/linear_algebra/vector-comparison.md @@ -16,11 +16,8 @@ This recipe also contains additional ownership examples. Here, `let z = a + b` c `let w = &c + &d` creates a new vector without consuming `c` or `d`, allowing their modification later. See [Binary Operators With Two Arrays] for additional detail. -```rust -#[macro_use(assert_abs_diff_eq)] -extern crate approx; -extern crate ndarray; - +```rust,edition2018 +use approx::assert_abs_diff_eq; use ndarray::Array; fn main() { diff --git a/src/science/mathematics/linear_algebra/vector-norm.md b/src/science/mathematics/linear_algebra/vector-norm.md index b1988fc..b9cbcd9 100644 --- a/src/science/mathematics/linear_algebra/vector-norm.md +++ b/src/science/mathematics/linear_algebra/vector-norm.md @@ -26,11 +26,8 @@ If the function is part of a public API, that may be a better choice for the benefit of users. For internal functions, the more concise `ArrayView1` may be preferable. -```rust -#[macro_use(array)] -extern crate ndarray; - -use ndarray::{Array1, ArrayView1}; +```rust,edition2018 +use ndarray::{array, Array1, ArrayView1}; fn l1_norm(x: ArrayView1) -> f64 { x.fold(0., |acc, elem| acc + elem.abs()) @@ -59,4 +56,4 @@ fn main() { [`dot`]: https://docs.rs/ndarray/*/ndarray/struct.ArrayBase.html#method.dot [`fold`]: https://docs.rs/ndarray/*/ndarray/struct.ArrayBase.html#method.fold [l1]: http://mathworld.wolfram.com/L1-Norm.html -[l2]: http://mathworld.wolfram.com/L2-Norm.html \ No newline at end of file +[l2]: http://mathworld.wolfram.com/L2-Norm.html diff --git a/src/science/mathematics/miscellaneous/big-integers.md b/src/science/mathematics/miscellaneous/big-integers.md index 19e2eaf..ac2f97b 100644 --- a/src/science/mathematics/miscellaneous/big-integers.md +++ b/src/science/mathematics/miscellaneous/big-integers.md @@ -4,9 +4,7 @@ Calculation for integers exceeding 128 bits are possible with [`BigInt`]. -```rust -extern crate num; - +```rust,edition2018 use num::bigint::{BigInt, ToBigInt}; fn factorial(x: i32) -> BigInt { diff --git a/src/science/mathematics/statistics/central-tendency.md b/src/science/mathematics/statistics/central-tendency.md index 8409290..cded239 100644 --- a/src/science/mathematics/statistics/central-tendency.md +++ b/src/science/mathematics/statistics/central-tendency.md @@ -6,7 +6,7 @@ These examples calculate measures of central tendency for a data set contained w The first example calculates the mean (the sum of all measurements divided by the number of measurements in the set) by producing an iterator of references over the data, and using [`sum`] and [`len`] to determine the total value and count of values respectively. -```rust +```rust,edition2018 fn main() { let data = [3, 1, 6, 1, 5, 8, 1, 8, 10, 11]; @@ -24,7 +24,7 @@ fn main() { The second example calculates the median using the quickselect algorithm, which avoids a full [`sort`] by sorting only partitions of the data set known to possibly contain the median. This uses [`cmp`] and [`Ordering`] to succinctly decide the next partition to examine, and [`split_at`] to choose an arbitrary pivot for the next partition at each step. -```rust +```rust,edition2018 use std::cmp::Ordering; fn partition(data: &[i32]) -> Option<(Vec, i32, Vec)> { @@ -101,7 +101,7 @@ fn main() { The final example calculates the mode using a mutable [`HashMap`] to collect counts of each distinct integer from the set, using a [`fold`] and the [`entry`] API. The most frequent value in the [`HashMap`] surfaces with [`max_by_key`]. -```rust +```rust,edition2018 use std::collections::HashMap; fn main() { diff --git a/src/science/mathematics/statistics/standard-deviation.md b/src/science/mathematics/statistics/standard-deviation.md index c023395..3d1eb9f 100644 --- a/src/science/mathematics/statistics/standard-deviation.md +++ b/src/science/mathematics/statistics/standard-deviation.md @@ -9,7 +9,7 @@ The standard deviation is defined as the square root of the variance (here calcu The z-score is the number of standard deviations a single measurement spans away from the [`mean`] of the data set. -```rust +```rust,edition2018 fn mean(data: &[i32]) -> Option { let sum = data.iter().sum::() as f32; let count = data.len(); diff --git a/src/science/mathematics/trigonometry/latitude-longitude.md b/src/science/mathematics/trigonometry/latitude-longitude.md index bc90aec..7432f16 100644 --- a/src/science/mathematics/trigonometry/latitude-longitude.md +++ b/src/science/mathematics/trigonometry/latitude-longitude.md @@ -13,7 +13,7 @@ converts them in radian. [`sin`], [`cos`], [`powi`] and [`sqrt`] compute the central angle. Finally, it's possible to calculate the distance. -```rust +```rust,edition2018 fn main() { let earth_radius_kilometer = 6371.0_f64; let (paris_latitude_degrees, paris_longitude_degrees) = (48.85341_f64, -2.34880_f64); diff --git a/src/science/mathematics/trigonometry/side-length.md b/src/science/mathematics/trigonometry/side-length.md index 0844e97..951329c 100644 --- a/src/science/mathematics/trigonometry/side-length.md +++ b/src/science/mathematics/trigonometry/side-length.md @@ -4,7 +4,7 @@ Calculates the length of the hypotenuse of a right-angle triangle with an angle of 2 radians and opposite side length of 80. -```rust +```rust,edition2018 fn main() { let angle: f64 = 2.0; let side_length = 80.0; diff --git a/src/science/mathematics/trigonometry/tan-sin-cos.md b/src/science/mathematics/trigonometry/tan-sin-cos.md index 6f3d1cc..59e71a8 100644 --- a/src/science/mathematics/trigonometry/tan-sin-cos.md +++ b/src/science/mathematics/trigonometry/tan-sin-cos.md @@ -4,7 +4,7 @@ Verifies tan(x) is equal to sin(x)/cos(x) for x = 6. -```rust +```rust,edition2018 fn main() { let x: f64 = 6.0; diff --git a/src/text/regex/email.md b/src/text/regex/email.md index d4338ce..3c3b254 100644 --- a/src/text/regex/email.md +++ b/src/text/regex/email.md @@ -5,10 +5,8 @@ Validates that an email address is formatted correctly, and extracts everything before the @ symbol. -```rust -#[macro_use] -extern crate lazy_static; -extern crate regex; +```rust,edition2018 +use lazy_static::lazy_static; use regex::Regex; diff --git a/src/text/regex/filter-log.md b/src/text/regex/filter-log.md index 68bc91c..bd179ef 100644 --- a/src/text/regex/filter-log.md +++ b/src/text/regex/filter-log.md @@ -10,10 +10,8 @@ A [`regex::RegexSetBuilder`] composes a [`regex::RegexSet`]. Since backslashes are very common in regular expressions, using [raw string literals] makes them more readable. -```rust,no_run -# #[macro_use] -# extern crate error_chain; -extern crate regex; +```rust,edition2018,no_run +# use error_chain::error_chain; use std::fs::File; use std::io::{BufReader, BufRead}; diff --git a/src/text/regex/hashtags.md b/src/text/regex/hashtags.md index 9d3061c..a79bb2e 100644 --- a/src/text/regex/hashtags.md +++ b/src/text/regex/hashtags.md @@ -7,10 +7,8 @@ Extracts, sorts, and deduplicates list of hashtags from text. The hashtag regex given here only catches Latin hashtags that start with a letter. The complete [twitter hashtag regex] is much more complicated. -```rust -extern crate regex; -#[macro_use] -extern crate lazy_static; +```rust,edition2018 +use lazy_static::lazy_static; use regex::Regex; use std::collections::HashSet; diff --git a/src/text/regex/phone.md b/src/text/regex/phone.md index d011adb..3a294fe 100644 --- a/src/text/regex/phone.md +++ b/src/text/regex/phone.md @@ -5,10 +5,8 @@ Processes a string of text using [`Regex::captures_iter`] to capture multiple phone numbers. The example here is for US convention phone numbers. -```rust -# #[macro_use] -# extern crate error_chain; -extern crate regex; +```rust,edition2018 +# use error_chain::error_chain; use regex::Regex; use std::fmt; diff --git a/src/text/regex/replace.md b/src/text/regex/replace.md index cc5ee43..d6b5226 100644 --- a/src/text/regex/replace.md +++ b/src/text/regex/replace.md @@ -11,10 +11,8 @@ The method [`Regex::replace_all`] replaces all occurrences of the whole regex. refer to corresponding named capture groups `(?PREGEX)` from the search regex. See the [replacement string syntax] for examples and escaping detail. -```rust -extern crate regex; -#[macro_use] -extern crate lazy_static; +```rust,edition2018 +use lazy_static::lazy_static; use std::borrow::Cow; use regex::Regex; diff --git a/src/text/string_parsing/from_str.md b/src/text/string_parsing/from_str.md index 0c91519..6bee31a 100644 --- a/src/text/string_parsing/from_str.md +++ b/src/text/string_parsing/from_str.md @@ -4,7 +4,7 @@ Creates a custom struct `RGB` and implements the `FromStr` trait to convert a provided color hex code into its RGB color code. -```rust +```rust,edition2018 use std::str::FromStr; #[derive(Debug, PartialEq)] diff --git a/src/text/string_parsing/graphemes.md b/src/text/string_parsing/graphemes.md index 99dff37..921c3c1 100644 --- a/src/text/string_parsing/graphemes.md +++ b/src/text/string_parsing/graphemes.md @@ -5,9 +5,7 @@ Collect individual Unicode graphemes from UTF-8 string using the [`UnicodeSegmentation::graphemes`] function from the [`unicode-segmentation`] crate. -```rust -#[macro_use] -extern crate unicode_segmentation; +```rust,edition2018 use unicode_segmentation::UnicodeSegmentation; fn main() { diff --git a/src/web/clients/api/paginated.md b/src/web/clients/api/paginated.md index fca752b..55d46c4 100644 --- a/src/web/clients/api/paginated.md +++ b/src/web/clients/api/paginated.md @@ -6,10 +6,8 @@ Wraps a paginated web API in a convenient Rust iterator. The iterator lazily fetches the next page of results from the remote server as it arrives at the end of each page. -```rust,no_run -#[macro_use] -extern crate serde_derive; -extern crate reqwest; +```rust,edition2018,no_run +use serde::Deserialize; use reqwest::Error; #[derive(Deserialize)] diff --git a/src/web/clients/api/rate-limited.md b/src/web/clients/api/rate-limited.md index 2deee48..21e8b60 100644 --- a/src/web/clients/api/rate-limited.md +++ b/src/web/clients/api/rate-limited.md @@ -7,12 +7,8 @@ handle remote server errors. This example uses the [`hyper::header!`] macro to parse the response header and checks for [`reqwest::StatusCode::Forbidden`]. If the response exceeds the rate limit, the example waits and retries. -```rust,no_run,ignore -# #[macro_use] -# extern crate error_chain; -#[macro_use] -extern crate hyper; -extern crate reqwest; +```rust,edition2018,no_run,ignore +# use error_chain::error_chain; use std::time::{Duration, UNIX_EPOCH}; use std::thread; diff --git a/src/web/clients/api/rest-get.md b/src/web/clients/api/rest-get.md index 2ba2452..cc7ac1b 100644 --- a/src/web/clients/api/rest-get.md +++ b/src/web/clients/api/rest-get.md @@ -5,11 +5,8 @@ Queries GitHub [stargazers API v3](https://developer.github.com/v3/activity/starring/#list-stargazers) with [`reqwest::get`] to get list of all users who have marked a GitHub project with a star. [`reqwest::Response`] is deserialized with [`Response::json`] into `User` objects implementing [`serde::Deserialize`]. -```rust,no_run -#[macro_use] -extern crate serde; -extern crate serde_derive; -extern crate reqwest; +```rust,edition2018,no_run +use serde::Deserialize; use reqwest::Error; #[derive(Deserialize, Debug)] diff --git a/src/web/clients/api/rest-head.md b/src/web/clients/api/rest-head.md index 6a795e0..04de301 100644 --- a/src/web/clients/api/rest-head.md +++ b/src/web/clients/api/rest-head.md @@ -8,8 +8,7 @@ success. This is a quick way to query a rest resource without needing to receive a body. [`reqwest::Client`] cofigured with [`ClientBuilder::timeout`] ensures a request will not last longer than a timeout. -```rust,no_run -extern crate reqwest; +```rust,edition2018,no_run use reqwest::Error; use std::time::Duration; diff --git a/src/web/clients/api/rest-post.md b/src/web/clients/api/rest-post.md index c97b30b..1782201 100644 --- a/src/web/clients/api/rest-post.md +++ b/src/web/clients/api/rest-post.md @@ -11,14 +11,10 @@ provides arbitrary JSON body. Call to [`RequestBuilder::json`] sets the request body. [`RequestBuilder::basic_auth`] handles authentication. The call to [`RequestBuilder::send`] synchronously executes the requests. -```rust,no_run -# #[macro_use] -# extern crate error_chain; -extern crate reqwest; -#[macro_use] -extern crate serde_derive; -#[macro_use] -extern crate serde_json; +```rust,edition2018,no_run +# use error_chain::error_chain; +use serde::Deserialize; + use serde_json::json; use std::env; use reqwest::Client; diff --git a/src/web/clients/download/basic.md b/src/web/clients/download/basic.md index 9eeb659..041a87f 100755 --- a/src/web/clients/download/basic.md +++ b/src/web/clients/download/basic.md @@ -9,11 +9,8 @@ Creates a target [`File`] with name obtained from [`Response::url`] within [`tempdir()`] and copies downloaded data into it with [`io::copy`]. The temporary directory is automatically removed on `run` function return. -```rust,no_run -# #[macro_use] -# extern crate error_chain; -extern crate reqwest; -extern crate tempfile; +```rust,edition2018,no_run +# use error_chain::error_chain; use std::io::copy; use std::fs::File; diff --git a/src/web/clients/download/partial.md b/src/web/clients/download/partial.md index 1427a79..980b8e6 100644 --- a/src/web/clients/download/partial.md +++ b/src/web/clients/download/partial.md @@ -9,10 +9,8 @@ chunks of 10240 bytes, while printing progress messages. The [Range] header spec The Range header is defined in [RFC7233][HTTP Range RFC7233]. -```rust,no_run -# #[macro_use] -# extern crate error_chain; -extern crate reqwest; +```rust,edition2018,no_run +# use error_chain::error_chain; use std::fs::File; use std::str::FromStr; @@ -86,7 +84,7 @@ fn main() -> Result<()> { let status = response.status(); if !(status == StatusCode::OK || status == StatusCode::PARTIAL_CONTENT) { - bail!("Unexpected server response: {}", status) + error_chain::bail!("Unexpected server response: {}", status) } std::io::copy(&mut response, &mut output_file)?; diff --git a/src/web/clients/download/post-file.md b/src/web/clients/download/post-file.md index c1d378d..3800542 100644 --- a/src/web/clients/download/post-file.md +++ b/src/web/clients/download/post-file.md @@ -9,11 +9,9 @@ content to send by reading the file, and [`RequestBuilder::send`] blocks until the file uploads and the response returns. [`read_to_string`] returns the response and displays in the console. -```rust,no_run -extern crate reqwest; +```rust,edition2018,no_run -# #[macro_use] -# extern crate error_chain; +# use error_chain::error_chain; # use std::fs::File; use std::io::Read; diff --git a/src/web/clients/requests/get.md b/src/web/clients/requests/get.md index bef5e3c..a262d23 100644 --- a/src/web/clients/requests/get.md +++ b/src/web/clients/requests/get.md @@ -7,10 +7,8 @@ with [`reqwest::get`]. Prints obtained [`reqwest::Response`] status and headers. Reads HTTP response body into an allocated [`String`] using [`read_to_string`]. -```rust,no_run -# #[macro_use] -# extern crate error_chain; -extern crate reqwest; +```rust,edition2018,no_run +# use error_chain::error_chain; use std::io::Read; # diff --git a/src/web/clients/requests/header.md b/src/web/clients/requests/header.md index 9cac074..7b1ba01 100644 --- a/src/web/clients/requests/header.md +++ b/src/web/clients/requests/header.md @@ -14,15 +14,9 @@ with [`RequestBuilder::header`] then makes the request with The request targets service which responds with a JSON dict containing all request headers for easy verification. -```rust,no_run,ignore -# #[macro_use] -# extern crate error_chain; -extern crate url; -extern crate reqwest; -#[macro_use] -extern crate hyper; -#[macro_use] -extern crate serde_derive; +```rust,edition2018,no_run,ignore +# use error_chain::error_chain; +use serde::Deserialize; use std::collections::HashMap; use url::Url; diff --git a/src/web/mime/filename.md b/src/web/mime/filename.md index 0aad928..6422d29 100644 --- a/src/web/mime/filename.md +++ b/src/web/mime/filename.md @@ -6,8 +6,7 @@ The following example shows how to return the correct MIME type from a given filename using the [mime] crate. The program will check for file extensions and match against a known list. The return value is [`mime:Mime`]. -```rust -extern crate mime; +```rust,edition2018 use mime::Mime; fn find_mimetype (filename : &String) -> Mime{ diff --git a/src/web/mime/request.md b/src/web/mime/request.md index 8bdeaaf..5f53838 100644 --- a/src/web/mime/request.md +++ b/src/web/mime/request.md @@ -11,11 +11,8 @@ The `mime` crate also defines some commonly used MIME types. Note that the [`reqwest::header`] module is exported from the [`http`] crate. -```rust,no_run -# #[macro_use] -# extern crate error_chain; -extern crate mime; -extern crate reqwest; +```rust,edition2018,no_run +# use error_chain::error_chain; use mime::Mime; use std::str::FromStr; diff --git a/src/web/mime/string.md b/src/web/mime/string.md index c1e6a0a..422921c 100644 --- a/src/web/mime/string.md +++ b/src/web/mime/string.md @@ -6,8 +6,7 @@ The following example shows how to parse a [`MIME`] type from a string using the [mime] crate. [`FromStrError`] produces a default [`MIME`] type in an `unwrap_or` clause. -```rust -extern crate mime; +```rust,edition2018 use mime::{Mime, APPLICATION_OCTET_STREAM}; fn main() { diff --git a/src/web/scraping/broken.md b/src/web/scraping/broken.md index ea25289..d813dce 100644 --- a/src/web/scraping/broken.md +++ b/src/web/scraping/broken.md @@ -10,12 +10,8 @@ Iterate through links in the document and parse with [`url::ParseOptions`] and [`Url::parse`]). Makes a request to the links with reqwest and verifies [`StatusCode`]. -```rust,no_run -# #[macro_use] -# extern crate error_chain; -extern crate reqwest; -extern crate select; -extern crate url; +```rust,edition2018,no_run +# use error_chain::error_chain; use std::collections::HashSet; diff --git a/src/web/scraping/extract-links.md b/src/web/scraping/extract-links.md index e6c9d36..2d9b567 100644 --- a/src/web/scraping/extract-links.md +++ b/src/web/scraping/extract-links.md @@ -8,11 +8,8 @@ Use [`reqwest::get`] to perform a HTTP GET request and then use Call [`filter_map`] on the [`Selection`] retrieves URLs from links that have the "href" [`attr`] (attribute). -```rust,no_run -# #[macro_use] -# extern crate error_chain; -extern crate reqwest; -extern crate select; +```rust,edition2018,no_run +# use error_chain::error_chain; use select::document::Document; use select::predicate::Name; diff --git a/src/web/scraping/unique.md b/src/web/scraping/unique.md index 1afe976..efae7f1 100644 --- a/src/web/scraping/unique.md +++ b/src/web/scraping/unique.md @@ -8,13 +8,9 @@ look for all entries of internal and external links with MediaWiki link syntax is described [here][MediaWiki link syntax]. -```rust,no_run -# #[macro_use] -# extern crate error_chain; -#[macro_use] -extern crate lazy_static; -extern crate reqwest; -extern crate regex; +```rust,edition2018,no_run +# use error_chain::error_chain; +use lazy_static::lazy_static; use std::io::Read; use std::collections::HashSet; diff --git a/src/web/url/base.md b/src/web/url/base.md index a1b1989..6897a73 100644 --- a/src/web/url/base.md +++ b/src/web/url/base.md @@ -7,10 +7,8 @@ files or query strings. Each of those items are stripped out of the given URL. [`PathSegmentsMut::clear`] removes paths and [`Url::set_query`] removes query string. -```rust -# #[macro_use] -# extern crate error_chain; -extern crate url; +```rust,edition2018 +# use error_chain::error_chain; use url::Url; # diff --git a/src/web/url/fragment.md b/src/web/url/fragment.md index e34733d..7ce0e6c 100644 --- a/src/web/url/fragment.md +++ b/src/web/url/fragment.md @@ -4,9 +4,8 @@ Parses [`Url`] and slices it with [`url::Position`] to strip unneeded URL parts. -```rust +```rust,edition2018 -extern crate url; use url::{Url, Position, ParseError}; diff --git a/src/web/url/new.md b/src/web/url/new.md index 669d76c..c657c35 100644 --- a/src/web/url/new.md +++ b/src/web/url/new.md @@ -4,8 +4,7 @@ The [`join`] method creates a new URL from a base and relative path. -```rust -extern crate url; +```rust,edition2018 use url::{Url, ParseError}; diff --git a/src/web/url/origin.md b/src/web/url/origin.md index dc10e18..e55b14d 100644 --- a/src/web/url/origin.md +++ b/src/web/url/origin.md @@ -5,8 +5,7 @@ The [`Url`] struct exposes various methods to extract information about the URL it represents. -```rust -extern crate url; +```rust,edition2018 use url::{Url, Host, ParseError}; @@ -26,10 +25,8 @@ fn main() -> Result<(), ParseError> { [`origin`] produces the same result. -```rust -# #[macro_use] -# extern crate error_chain; -extern crate url; +```rust,edition2018 +# use error_chain::error_chain; use url::{Url, Origin, Host}; diff --git a/src/web/url/parse.md b/src/web/url/parse.md index d3f0817..0da6b62 100644 --- a/src/web/url/parse.md +++ b/src/web/url/parse.md @@ -9,8 +9,7 @@ The [`parse`] method from the `url` crate validates and parses a `&str` into a Once the URL has been parsed, it can be used with all of the methods in the `Url` type. -```rust -extern crate url; +```rust,edition2018 use url::{Url, ParseError}; diff --git a/theme/index.hbs b/theme/index.hbs deleted file mode 100644 index d8242b9..0000000 --- a/theme/index.hbs +++ /dev/null @@ -1,261 +0,0 @@ - - - - - - {{ title }} - - - - - - - - - - - - - - - - - - - - - - {{#each additional_css}} - - {{/each}} - - {{#if mathjax_support}} - - - {{/if}} - - - - - - - - - - - - - - -
- -
- {{> header}} - - - {{#if search_enabled}} - - {{/if}} - - - - -
-
- {{{ content }}} -
- - -
-
- - - -
- - {{#if livereload}} - - - {{/if}} - - {{#if google_analytics}} - - - {{/if}} - - {{#if is_print}} - - {{/if}} - - {{#if playpen_js}} - - - - - - {{/if}} - - {{#if search_enabled}} - - {{/if}} - {{#if search_js}} - - - - {{/if}} - - - - - - - {{#each additional_js}} - - {{/each}} - - -