diff --git a/README.md b/README.md
index 54e92f6f8f..57d9be605e 100644
--- a/README.md
+++ b/README.md
@@ -1,30 +1,31 @@
-# The Rust Programming Language
+# El lenguaje de programación Rust
-
+
-This repository contains the source of "The Rust Programming Language" book.
+Este repositorio contiene el código fuente del libro "The Rust Programming Language".
-[The book is available in dead-tree form from No Starch Press][nostarch].
+[El libro está disponible en formato de archivo fijo en No Starch Press.][nostarch].
[nostarch]: https://nostarch.com/rust
-You can also read the book for free online. Please see the book as shipped with
-the latest [stable], [beta], or [nightly] Rust releases. Be aware that issues
-in those versions may have been fixed in this repository already, as those
-releases are updated less frequently.
+También puede leer el libro gratuitamente en línea. Por favor, vea el libro tal y como se envía con
+las últimas versiones [estable], [beta], o [nightly] Ten en cuenta que los problemas
+ de esas versiones pueden haber sido ya corregidos en este repositorio, ya que esas
+ versiones se actualizan con menos frecuencia.
-[stable]: https://doc.rust-lang.org/stable/book/
+[estable]: https://doc.rust-lang.org/stable/book/
[beta]: https://doc.rust-lang.org/beta/book/
[nightly]: https://doc.rust-lang.org/nightly/book/
-See the [releases] to download just the code of all the code listings that appear in the book.
+Vea las [versiones] para descargar sólo el código de todos los listados de código que aparecen en el libro.
-[releases]: https://github.com/rust-lang/book/releases
+[versiones]: https://github.com/rust-lang/book/releases
-## Requirements
+## Requisitos
+
+La construcción del libro requiere [mdBook], preferiblemente la misma versión que
+utiliza rust-lang/rust en [este archivo][rust-mdbook]. Para conseguirlo:
-Building the book requires [mdBook], ideally the same version that
-rust-lang/rust uses in [this file][rust-mdbook]. To get it:
[mdBook]: https://github.com/rust-lang-nursery/mdBook
[rust-mdbook]: https://github.com/rust-lang/rust/blob/master/src/tools/rustbook/Cargo.toml
@@ -33,16 +34,16 @@ rust-lang/rust uses in [this file][rust-mdbook]. To get it:
$ cargo install mdbook --vers [version-num]
```
-## Building
+## crear
-To build the book, type:
+Para crear el libro, escriba:
```bash
$ mdbook build
```
-The output will be in the `book` subdirectory. To check it out, open it in
-your web browser.
+El resultado estará en el subdirectorio del `book`. Para comprobarlo, ábralo en
+su navegador web.
_Firefox:_
```bash
@@ -60,34 +61,35 @@ $ Start-Process "chrome.exe" .\book\index.html # Windows (PowerShell)
$ start chrome.exe .\book\index.html # Windows (Cmd)
```
-To run the tests:
-
+Para ejecutar las pruebas:
```bash
$ mdbook test
```
-## Contributing
+## Forma de colaborar
-We'd love your help! Please see [CONTRIBUTING.md][contrib] to learn about the
-kinds of contributions we're looking for.
+Nos encantaría que nos ayudaras.[CONTRIBUTING.md][contrib] ara conocer el tipo de
+contribuciones que buscamos.
[contrib]: https://github.com/rust-lang/book/blob/master/CONTRIBUTING.md
-### Translations
+### Traducciones
+
+Nos encantaría que nos ayudaras a traducir el libro. Consulte la etiqueta [Traducciones]
+para unirse a los esfuerzos que se están llevando a cabo actualmente. Abra una nueva edición
+para empezar a trabajar en un nuevo idioma. Estamos esperando a que el [mdbook] sea
+compatible con varios idiomas antes de fusionar alguno, pero ¡no dudes en empezar!
+Revisión ortográfica
-We'd love help translating the book! See the [Translations] label to join in
-efforts that are currently in progress. Open a new issue to start working on
-a new language! We're waiting on [mdbook support] for multiple languages
-before we merge any in, but feel free to start!
+[Traducciones]: https://github.com/rust-lang/book/issues?q=is%3Aopen+is%3Aissue+label%3ATranslations
+[mdbook]: https://github.com/rust-lang-nursery/mdBook/issues/5
-[Translations]: https://github.com/rust-lang/book/issues?q=is%3Aopen+is%3Aissue+label%3ATranslations
-[mdbook support]: https://github.com/rust-lang-nursery/mdBook/issues/5
+## Revisión ortográfica
-## Spellchecking
+Para analizar los archivos fuente en busca de errores ortográficos,
+puede utilizar el script `spellcheck.sh` disponible en el directorio `ci`.
+Necesita un diccionario de palabras válidas, que se proporciona en `ci/dictionary.txt.`
+Si el script produce un falso positivo (por ejemplo, usted utilizó la palabra `
+BTreeMap`, que el script considera inválida), debe añadiresta
+palabra a `ci/dictionary.txt`(mantenga el orden ordenado para mantener la coherencia).
-To scan source files for spelling errors, you can use the `spellcheck.sh`
-script available in the `ci` directory. It needs a dictionary of valid words,
-which is provided in `ci/dictionary.txt`. If the script produces a false
-positive (say, you used word `BTreeMap` which the script considers invalid),
-you need to add this word to `ci/dictionary.txt` (keep the sorted order for
-consistency).
diff --git a/listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs b/listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs
index b822b89ff3..caf2ec525d 100644
--- a/listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs
+++ b/listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs
@@ -7,25 +7,25 @@ use std::io;
fn main() {
// ANCHOR_END: main
// ANCHOR: print
- println!("Guess the number!");
+ println!("¡Adivina el número!");
- println!("Please input your guess.");
+ println!("Por favor, introduce tu predicción.");
// ANCHOR_END: print
// ANCHOR: string
- let mut guess = String::new();
+ let mut prediccion = String::new();
// ANCHOR_END: string
// ANCHOR: read
io::stdin()
- .read_line(&mut guess)
+ .read_line(&mut prediccion)
// ANCHOR_END: read
// ANCHOR: expect
- .expect("Failed to read line");
+ .expect("Lectura de línea fallida");
// ANCHOR_END: expect
// ANCHOR: print_guess
- println!("You guessed: {}", guess);
+ println!("Predijiste: {}", prediccion);
// ANCHOR_END: print_guess
}
// ANCHOR: all
diff --git a/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/src/main.rs b/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/src/main.rs
index e7a11a969c..247edea12b 100644
--- a/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/src/main.rs
+++ b/listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/src/main.rs
@@ -1,3 +1,3 @@
fn main() {
- println!("Hello, world!");
+ println!("¡Hola, mundo!");
}
diff --git a/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/src/main.rs b/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/src/main.rs
index aaf90bd659..23b976eb75 100644
--- a/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/src/main.rs
+++ b/listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/src/main.rs
@@ -1,13 +1,13 @@
use std::io;
fn main() {
- println!("Guess the number!");
+ println!("¡Adivina el número!");
- println!("Please input your guess.");
+ println!("Por favor, introduce tu predicción.");
- let mut guess = String::new();
+ let mut prediccion = String::new();
- io::stdin().read_line(&mut guess);
+ io::stdin().read_line(&mut prediccion);
- println!("You guessed: {}", guess);
+ println!("Predijiste: {}", prediccion);
}
diff --git a/src/SUMMARY.md b/src/SUMMARY.md
index a9b8feb00a..4aa4907656 100644
--- a/src/SUMMARY.md
+++ b/src/SUMMARY.md
@@ -1,39 +1,39 @@
-# The Rust Programming Language
+# El lenguaje de programación Rust
-[The Rust Programming Language](title-page.md)
-[Foreword](foreword.md)
-[Introduction](ch00-00-introduction.md)
+[El lenguaje de programación Rust](title-page.md)
+[Prólogo](foreword.md)
+[Introducción](ch00-00-introduction.md)
-## Getting started
+## Cómo empezar
-- [Getting Started](ch01-00-getting-started.md)
- - [Installation](ch01-01-installation.md)
- - [Hello, World!](ch01-02-hello-world.md)
- - [Hello, Cargo!](ch01-03-hello-cargo.md)
+- [Cómo empezar](ch01-00-getting-started.md)
+ - [Instalación](ch01-01-installation.md)
+ - [¡Hola, mundo!](ch01-02-hello-world.md)
+ - [¡Hola, Cargo!](ch01-03-hello-cargo.md)
-- [Programming a Guessing Game](ch02-00-guessing-game-tutorial.md)
+- [Programación de un juego de adivinanzas](ch02-00-guessing-game-tutorial.md)
-- [Common Programming Concepts](ch03-00-common-programming-concepts.md)
- - [Variables and Mutability](ch03-01-variables-and-mutability.md)
- - [Data Types](ch03-02-data-types.md)
- - [Functions](ch03-03-how-functions-work.md)
- - [Comments](ch03-04-comments.md)
- - [Control Flow](ch03-05-control-flow.md)
+- [Conceptos básicos de programación](ch03-00-common-programming-concepts.md)
+ - [Variables y mutabilidad](ch03-01-variables-and-mutability.md)
+ - [Tipos de datos](ch03-02-data-types.md)
+ - [Funciones](ch03-03-how-functions-work.md)
+ - [Comentarios](ch03-04-comments.md)
+ - [Control de flujo](ch03-05-control-flow.md)
-- [Understanding Ownership](ch04-00-understanding-ownership.md)
- - [What is Ownership?](ch04-01-what-is-ownership.md)
+- [Comprensión de la propiedad](ch04-00-understanding-ownership.md)
+ - [¿Qué es la propiedad?](ch04-01-what-is-ownership.md)
- [References and Borrowing](ch04-02-references-and-borrowing.md)
- - [The Slice Type](ch04-03-slices.md)
+ - [El Tipo Slice](ch04-03-slices.md)
-- [Using Structs to Structure Related Data](ch05-00-structs.md)
- - [Defining and Instantiating Structs](ch05-01-defining-structs.md)
- - [An Example Program Using Structs](ch05-02-example-structs.md)
- - [Method Syntax](ch05-03-method-syntax.md)
+- [Uso de Structs para Estructurar Datos Relacionados](ch05-00-structs.md)
+ - [Definición e Instanciación de Structs](ch05-01-defining-structs.md)
+ - [Un Programa de Ejemplo con Structs](ch05-02-example-structs.md)
+ - [Sintaxis de Métodos](ch05-03-method-syntax.md)
-- [Enums and Pattern Matching](ch06-00-enums.md)
- - [Defining an Enum](ch06-01-defining-an-enum.md)
+- [Enums y Comparación de Patrones](ch06-00-enums.md)
+ - [Definición de un Enum](ch06-01-defining-an-enum.md)
- [The `match` Control Flow Operator](ch06-02-match.md)
- - [Concise Control Flow with `if let`](ch06-03-if-let.md)
+ - [Flujo de Control Conciso con `if let`](ch06-03-if-let.md)
## Basic Rust Literacy
@@ -125,11 +125,11 @@
- [Turning Our Single-Threaded Server into a Multithreaded Server](ch20-02-multithreaded.md)
- [Graceful Shutdown and Cleanup](ch20-03-graceful-shutdown-and-cleanup.md)
-- [Appendix](appendix-00.md)
- - [A - Keywords](appendix-01-keywords.md)
- - [B - Operators and Symbols](appendix-02-operators.md)
+- [Apéndice](appendix-00.md)
+ - [A - Palabras clave](appendix-01-keywords.md)
+ - [B - Operadores y símbolos](appendix-02-operators.md)
- [C - Derivable Traits](appendix-03-derivable-traits.md)
- - [D - Useful Development Tools](appendix-04-useful-development-tools.md)
- - [E - Editions](appendix-05-editions.md)
- - [F - Translations of the Book](appendix-06-translation.md)
- - [G - How Rust is Made and “Nightly Rust”](appendix-07-nightly-rust.md)
+ - [D - Herramientas de desarrollo útiles](appendix-04-useful-development-tools.md)
+ - [E - Ediciones](appendix-05-editions.md)
+ - [F - Traducciones del libro](appendix-06-translation.md)
+ - [G - Cómo se hizo Rust y “Nightly Rust”](appendix-07-nightly-rust.md)
diff --git a/src/appendix-00.md b/src/appendix-00.md
index 83a7e91329..1ad9c88c6c 100644
--- a/src/appendix-00.md
+++ b/src/appendix-00.md
@@ -1,4 +1,4 @@
-# Appendix
+# Anexo
-The following sections contain reference material you may find useful in your
-Rust journey.
+Las siguientes secciones contienen material de referencia que puede resultar útil en su
+en su viaje por Rust.
diff --git a/src/appendix-01-keywords.md b/src/appendix-01-keywords.md
index c609cb4b99..b724eb33fc 100644
--- a/src/appendix-01-keywords.md
+++ b/src/appendix-01-keywords.md
@@ -1,4 +1,4 @@
-## Appendix A: Keywords
+## Anexo A: Palabras clave
The following list contains keywords that are reserved for current or future
use by the Rust language. As such, they cannot be used as identifiers (except
@@ -9,59 +9,59 @@ macros, static values, attributes, types, traits, or lifetimes.
[raw-identifiers]: #raw-identifiers
-### Keywords Currently in Use
-
-The following keywords currently have the functionality described.
-
-* `as` - perform primitive casting, disambiguate the specific trait containing
- an item, or rename items in `use` and `extern crate` statements
-* `async` - return a `Future` instead of blocking the current thread
-* `await` - suspend execution until the result of a `Future` is ready
-* `break` - exit a loop immediately
-* `const` - define constant items or constant raw pointers
-* `continue` - continue to the next loop iteration
-* `crate` - link an external crate or a macro variable representing the crate in
- which the macro is defined
-* `dyn` - dynamic dispatch to a trait object
-* `else` - fallback for `if` and `if let` control flow constructs
-* `enum` - define an enumeration
-* `extern` - link an external crate, function, or variable
+### Palabras clave actualmente en uso
+
+Las siguientes palabras clave tienen actualmente la funcionalidad descrita.
+
+* `as` - realizar un casting primitivo, desambiguar el rasgo específico que contiene
+ un elemento, o cambiar el nombre de los elementos en las declaraciones `use` y `extern crate`.
+* `async` - retornar un `Future` en lugar de bloquear el hilo actual
+* `await` - suspender la ejecución hasta que el resultado de un `Future` esté listo
+* `break` - salir inmediatamente de un bucle
+* `const` - definir elementos constantes o punteros crudos constantes
+* `continue` - continuar con la siguiente iteración del bucle
+* `crate` - vincular un crate externo o una variable de macro que represente el crate en
+ en el que está definida la macro
+* `dyn` - envío dinámico a un objeto trait
+* `else` - la respuesta a las construcciones de flujo de control "if" y "if let".
+* `enum` - definir una enumeración
+* `extern` - vincular una caja, función o variable externa
* `false` - Boolean false literal
-* `fn` - define a function or the function pointer type
-* `for` - loop over items from an iterator, implement a trait, or specify a
- higher-ranked lifetime
-* `if` - branch based on the result of a conditional expression
-* `impl` - implement inherent or trait functionality
-* `in` - part of `for` loop syntax
-* `let` - bind a variable
-* `loop` - loop unconditionally
-* `match` - match a value to patterns
-* `mod` - define a module
-* `move` - make a closure take ownership of all its captures
-* `mut` - denote mutability in references, raw pointers, or pattern bindings
-* `pub` - denote public visibility in struct fields, `impl` blocks, or modules
-* `ref` - bind by reference
-* `return` - return from function
-* `Self` - a type alias for the type we are defining or implementing
-* `self` - method subject or current module
-* `static` - global variable or lifetime lasting the entire program execution
-* `struct` - define a structure
-* `super` - parent module of the current module
-* `trait` - define a trait
-* `true` - Boolean true literal
-* `type` - define a type alias or associated type
-* `union` - define a [union] and is only a keyword when used in a union declaration
-* `unsafe` - denote unsafe code, functions, traits, or implementations
-* `use` - bring symbols into scope
-* `where` - denote clauses that constrain a type
-* `while` - loop conditionally based on the result of an expression
+* `fn` - definir una función o el tipo de puntero de función
+* `for` - bucle sobre los elementos de un iterador, implementar un rasgo, o especificar un
+ tiempo de duración mayor
+* `if` - rama basada en el resultado de una expresión condicional
+* `impl` - implementar la funcionalidad inherente o de rasgo
+* `in` - parte de la sintaxis del bucle `for`.
+* `let` - enlazar una variable
+* `loop` - bucle de forma incondicional
+* `match` - hacer coincidir un valor con los patrones
+* `mod` - definir un módulo
+* `move` - hacer que las capturas de un cierre sean de su propiedad
+* `mut` - denotan la mutabilidad en las referencias, los punteros en bruto o los enlaces de patrones
+* `pub` - denotan la visibilidad pública en campos struct, bloques `impl` o módulos
+* `ref` - enlazar por referencia
+* `return` - retorno de la función
+* `Self` - un nombre de tipo para el tipo que estamos definiendo o implementando
+* `self` - método tema o módulo actual
+* `static` - variable global o el tiempo de vida que dura toda la ejecución del programa
+* `struct` - definir una estructura
+* `super` - módulo padre del módulo actual
+* `trait` - definir una trait
+* `true` - Booleano verdadero
+* `type` - definir un nombre de tipo o un tipo asociado
+* `union` - definen una [union] y sólo es una palabra clave cuando se utiliza en una declaración de unión
+* `unsafe` - denotan código, funciones, rasgos o implementaciones no seguras
+* `use` - introducir los símbolos en el ámbito de aplicación
+* `where` - denotan declaraciones que restringen un tipo
+* `while` - bucle condicional basado en el resultado de una expresión
[union]: ../reference/items/unions.html
-### Keywords Reserved for Future Use
+### Palabras clave reservadas para uso futuro
-The following keywords do not have any functionality but are reserved by Rust
-for potential future use.
+Las siguientes palabras clave no tienen ninguna funcionalidad pero están reservadas por Rust
+para un posible uso futuro.
* `abstract`
* `become`
@@ -77,13 +77,13 @@ for potential future use.
* `virtual`
* `yield`
-### Raw Identifiers
+### Identificadores en bruto
-*Raw identifiers* are the syntax that lets you use keywords where they wouldn’t
-normally be allowed. You use a raw identifier by prefixing a keyword with `r#`.
+*Los identificadores brutos* son la sintaxis que permite utilizar palabras clave donde normalmente no se
+normalmente se permiten. Para utilizar un identificador sin procesar, hay que anteponer a la palabra clave `r#`
-For example, `match` is a keyword. If you try to compile the following function
-that uses `match` as its name:
+Por ejemplo, `match` es una palabra clave. Si intenta compilar la siguiente función
+que utiliza `match` como nombre:
Filename: src/main.rs
@@ -93,7 +93,7 @@ fn match(needle: &str, haystack: &str) -> bool {
}
```
-you’ll get this error:
+obtendrá este error:
```text
error: expected identifier, found keyword `match`
@@ -103,9 +103,9 @@ error: expected identifier, found keyword `match`
| ^^^^^ expected identifier, found keyword
```
-The error shows that you can’t use the keyword `match` as the function
-identifier. To use `match` as a function name, you need to use the raw
-identifier syntax, like this:
+El error muestra que no se puede utilizar la palabra clave `match` como identificador de la función
+como identificador de la función. Para utilizar `match` como nombre de función, es necesario utilizar la sintaxis de identificador
+sintaxis del identificador, así:
Filename: src/main.rs
@@ -119,16 +119,19 @@ fn main() {
}
```
-This code will compile without any errors. Note the `r#` prefix on the function
-name in its definition as well as where the function is called in `main`.
-
-Raw identifiers allow you to use any word you choose as an identifier, even if
-that word happens to be a reserved keyword. In addition, raw identifiers allow
-you to use libraries written in a different Rust edition than your crate uses.
-For example, `try` isn’t a keyword in the 2015 edition but is in the 2018
-edition. If you depend on a library that’s written using the 2015 edition and
-has a `try` function, you’ll need to use the raw identifier syntax, `r#try` in
-this case, to call that function from your 2018 edition code. See [Appendix
-E][appendix-e] for more information on editions.
+Este código se compilará sin ningún error. Observe el prefijo `r#` en el nombre de la función
+en su definición, así como el lugar donde se llama a la función en `main`.
+
+Los identificadores en bruto le permiten utilizar cualquier palabra que elija como identificador, incluso si esa palabra sea
+una palabra clave reservada. Además, los identificadores sin procesar le permiten
+utilizar bibliotecas escritas en una edición de Rust diferente a la que utiliza tu crate.
+Por ejemplo, " try " no es una palabra clave en la edición de 2015 pero sí en la de 2018
+2018. Si depende de una biblioteca escrita con la edición de 2015 y
+tiene una función `try`, tendrá que utilizar la sintaxis del identificador bruto, `r#try` en
+en este caso, para llamar a esa función desde tu código de la edición 2018. Véase en [Appendix
+E][appendix-e]para más información sobre las ediciones.
+
+
+
[appendix-e]: appendix-05-editions.html
diff --git a/src/appendix-02-operators.md b/src/appendix-02-operators.md
index 965b2371f5..971f64081b 100644
--- a/src/appendix-02-operators.md
+++ b/src/appendix-02-operators.md
@@ -1,45 +1,45 @@
-## Appendix B: Operators and Symbols
+## Apéndice B: Operadores y símbolos
-This appendix contains a glossary of Rust’s syntax, including operators and
-other symbols that appear by themselves or in the context of paths, generics,
-trait bounds, macros, attributes, comments, tuples, and brackets.
+Este apéndice contiene un glosario de la sintaxis de Rust, incluyendo operadores y
+otros símbolos que aparecen por sí mismos o en el contexto de rutas, genéricos
+límites de rasgos, macros, atributos, comentarios, tuplas y paréntesis.
-### Operators
+### Operadores
-Table B-1 contains the operators in Rust, an example of how the operator would
-appear in context, a short explanation, and whether that operator is
-overloadable. If an operator is overloadable, the relevant trait to use to
-overload that operator is listed.
+La Tabla B-1 contiene los operadores en Rust, un ejemplo de cómo el operador aparecería en el contexto, una breve explicación y si el operador
+en contexto, una breve explicación y si el operador es sobrecargable.
+sobrecargable. Si un operador es sobrecargable, el rasgo relevante a utilizar para
+para sobrecargar ese operador.
-Table B-1: Operators
+Tabla B-1: Operadores
-| Operator | Example | Explanation | Overloadable? |
+| Operador | Ejemplo | Explicación | ¿Sobrecargable? |
|----------|---------|-------------|---------------|
-| `!` | `ident!(...)`, `ident!{...}`, `ident![...]` | Macro expansion | |
-| `!` | `!expr` | Bitwise or logical complement | `Not` |
-| `!=` | `var != expr` | Nonequality comparison | `PartialEq` |
-| `%` | `expr % expr` | Arithmetic remainder | `Rem` |
-| `%=` | `var %= expr` | Arithmetic remainder and assignment | `RemAssign` |
-| `&` | `&expr`, `&mut expr` | Borrow | |
-| `&` | `&type`, `&mut type`, `&'a type`, `&'a mut type` | Borrowed pointer type | |
-| `&` | `expr & expr` | Bitwise AND | `BitAnd` |
-| `&=` | `var &= expr` | Bitwise AND and assignment | `BitAndAssign` |
+| `!` | `ident!(...)`, `ident!{...}`, `ident![...]` | Expansión de macros | |
+| `!` | `!expr` | Complemento lógico o de bit a bit | `Not` |
+| `!=` | `var != expr` | Comparación sin calidad | `PartialEq` |
+| `%` | `expr % expr` | Residuo aritmético | `Rem` |
+| `%=` | `var %= expr` | Residuo aritmético y asignación | `RemAssign` |
+| `&` | `&expr`, `&mut expr` | "Prestado" | |
+| `&` | `&type`, `&mut type`, `&'a type`, `&'a mut type` | Type de puntero "prestado" | |
+| `&` | `expr & expr` | AND a nivel de bits | `BitAnd` |
+| `&=` | `var &= expr` | Asignación y AND a nivel de bit | `BitAndAssign` |
| `&&` | `expr && expr` | Short-circuiting logical AND | |
-| `*` | `expr * expr` | Arithmetic multiplication | `Mul` |
-| `*=` | `var *= expr` | Arithmetic multiplication and assignment | `MulAssign` |
-| `*` | `*expr` | Dereference | |
-| `*` | `*const type`, `*mut type` | Raw pointer | |
-| `+` | `trait + trait`, `'a + trait` | Compound type constraint | |
-| `+` | `expr + expr` | Arithmetic addition | `Add` |
-| `+=` | `var += expr` | Arithmetic addition and assignment | `AddAssign` |
-| `,` | `expr, expr` | Argument and element separator | |
-| `-` | `- expr` | Arithmetic negation | `Neg` |
-| `-` | `expr - expr` | Arithmetic subtraction | `Sub` |
-| `-=` | `var -= expr` | Arithmetic subtraction and assignment | `SubAssign` |
-| `->` | `fn(...) -> type`, |...| -> type | Function and closure return type | |
-| `.` | `expr.ident` | Member access | |
+| `*` | `expr * expr` | Multiplicación aritmética | `Mul` |
+| `*=` | `var *= expr` | Multiplicación aritmética y asignación | `MulAssign` |
+| `*` | `*expr` | Dereferir | |
+| `*` | `*const type`, `*mut type` | Puntero crudo | |
+| `+` | `trait + trait`, `'a + trait` | Condición de tipo combinado | |
+| `+` | `expr + expr` | Adición aritmética | `Add` |
+| `+=` | `var += expr` | Adición y asignación aritmética | `AddAssign` |
+| `,` | `expr, expr` | Separador de argumentos y elementos | |
+| `-` | `- expr` | Negativo aritmético | `Neg` |
+| `-` | `expr - expr` | Resta aritmética | `Sub` |
+| `-=` | `var -= expr` | Resta y asignación aritmética | `SubAssign` |
+| `->` | `fn(...) -> type`, |...| -> type | Tipo de retorno de funciones y cierres | |
+| `.` | `expr.ident` | Acceso a miembros | |
| `..` | `..`, `expr..`, `..expr`, `expr..expr` | Right-exclusive range literal | |
-| `..=` | `..=expr`, `expr..=expr` | Right-inclusive range literal | |
+| `..=` | `..=expr`, `expr..=expr` | Derecha-incluyente literal de rango | |
| `..` | `..expr` | Struct literal update syntax | |
| `..` | `variant(x, ..)`, `struct_type { x, .. }` | “And the rest” pattern binding | |
| `...` | `expr...expr` | In a pattern: inclusive range pattern | |
@@ -70,13 +70,13 @@ overload that operator is listed.
| || | expr || expr | Short-circuiting logical OR | |
| `?` | `expr?` | Error propagation | |
-### Non-operator Symbols
+### Símbolos no operativos
-The following list contains all non-letters that don’t function as operators;
-that is, they don’t behave like a function or method call.
+La siguiente lista contiene todas las letras que no funcionan como operadores;
+es decir, no se comportan como una llamada a una función o método.
-Table B-2 shows symbols that appear on their own and are valid in a variety of
-locations.
+La Tabla B-2 muestra los símbolos que aparecen solos y que son válidos en una variedad de
+lugares.
Table B-2: Stand-Alone Syntax
diff --git a/src/appendix-03-derivable-traits.md b/src/appendix-03-derivable-traits.md
index bc20ab107e..0ccba59e2d 100644
--- a/src/appendix-03-derivable-traits.md
+++ b/src/appendix-03-derivable-traits.md
@@ -1,182 +1,156 @@
-## Appendix C: Derivable Traits
-
-In various places in the book, we’ve discussed the `derive` attribute, which
-you can apply to a struct or enum definition. The `derive` attribute generates
-code that will implement a trait with its own default implementation on the
-type you’ve annotated with the `derive` syntax.
-
-In this appendix, we provide a reference of all the traits in the standard
-library that you can use with `derive`. Each section covers:
-
-* What operators and methods deriving this trait will enable
-* What the implementation of the trait provided by `derive` does
-* What implementing the trait signifies about the type
-* The conditions in which you’re allowed or not allowed to implement the trait
-* Examples of operations that require the trait
-
-If you want different behavior from that provided by the `derive` attribute,
-consult the [standard library documentation](../std/index.html)
-for each trait for details of how to manually implement them.
-
-The rest of the traits defined in the standard library can’t be implemented on
-your types using `derive`. These traits don’t have sensible default behavior,
-so it’s up to you to implement them in the way that makes sense for what you’re
-trying to accomplish.
-
-An example of a trait that can’t be derived is `Display`, which handles
-formatting for end users. You should always consider the appropriate way to
-display a type to an end user. What parts of the type should an end user be
-allowed to see? What parts would they find relevant? What format of the data
-would be most relevant to them? The Rust compiler doesn’t have this insight, so
-it can’t provide appropriate default behavior for you.
-
-The list of derivable traits provided in this appendix is not comprehensive:
-libraries can implement `derive` for their own traits, making the list of
-traits you can use `derive` with truly open-ended. Implementing `derive`
-involves using a procedural macro, which is covered in the
-[“Macros”][macros] section of Chapter 19.
-
-### `Debug` for Programmer Output
-
-The `Debug` trait enables debug formatting in format strings, which you
-indicate by adding `:?` within `{}` placeholders.
-
-The `Debug` trait allows you to print instances of a type for debugging
-purposes, so you and other programmers using your type can inspect an instance
-at a particular point in a program’s execution.
-
-The `Debug` trait is required, for example, in use of the `assert_eq!` macro.
-This macro prints the values of instances given as arguments if the equality
-assertion fails so programmers can see why the two instances weren’t equal.
-
-### `PartialEq` and `Eq` for Equality Comparisons
-
-The `PartialEq` trait allows you to compare instances of a type to check for
-equality and enables use of the `==` and `!=` operators.
-
-Deriving `PartialEq` implements the `eq` method. When `PartialEq` is derived on
-structs, two instances are equal only if *all* fields are equal, and the
-instances are not equal if any fields are not equal. When derived on enums,
-each variant is equal to itself and not equal to the other variants.
-
-The `PartialEq` trait is required, for example, with the use of the
-`assert_eq!` macro, which needs to be able to compare two instances of a type
-for equality.
-
-The `Eq` trait has no methods. Its purpose is to signal that for every value of
-the annotated type, the value is equal to itself. The `Eq` trait can only be
-applied to types that also implement `PartialEq`, although not all types that
-implement `PartialEq` can implement `Eq`. One example of this is floating point
-number types: the implementation of floating point numbers states that two
-instances of the not-a-number (`NaN`) value are not equal to each other.
-
-An example of when `Eq` is required is for keys in a `HashMap` so the
-`HashMap` can tell whether two keys are the same.
-
-### `PartialOrd` and `Ord` for Ordering Comparisons
-
-The `PartialOrd` trait allows you to compare instances of a type for sorting
-purposes. A type that implements `PartialOrd` can be used with the `<`, `>`,
-`<=`, and `>=` operators. You can only apply the `PartialOrd` trait to types
-that also implement `PartialEq`.
-
-Deriving `PartialOrd` implements the `partial_cmp` method, which returns an
-`Option` that will be `None` when the values given don’t produce an
-ordering. An example of a value that doesn’t produce an ordering, even though
-most values of that type can be compared, is the not-a-number (`NaN`) floating
-point value. Calling `partial_cmp` with any floating point number and the `NaN`
-floating point value will return `None`.
-
-When derived on structs, `PartialOrd` compares two instances by comparing the
-value in each field in the order in which the fields appear in the struct
-definition. When derived on enums, variants of the enum declared earlier in the
-enum definition are considered less than the variants listed later.
-
-The `PartialOrd` trait is required, for example, for the `gen_range` method
-from the `rand` crate that generates a random value in the range specified by a
-range expression.
-
-The `Ord` trait allows you to know that for any two values of the annotated
-type, a valid ordering will exist. The `Ord` trait implements the `cmp` method,
-which returns an `Ordering` rather than an `Option` because a valid
-ordering will always be possible. You can only apply the `Ord` trait to types
-that also implement `PartialOrd` and `Eq` (and `Eq` requires `PartialEq`). When
-derived on structs and enums, `cmp` behaves the same way as the derived
-implementation for `partial_cmp` does with `PartialOrd`.
-
-An example of when `Ord` is required is when storing values in a `BTreeSet`,
-a data structure that stores data based on the sort order of the values.
-
-### `Clone` and `Copy` for Duplicating Values
-
-The `Clone` trait allows you to explicitly create a deep copy of a value, and
-the duplication process might involve running arbitrary code and copying heap
-data. See the [“Ways Variables and Data Interact:
-Clone”][ways-variables-and-data-interact-clone] section in
-Chapter 4 for more information on `Clone`.
-
-Deriving `Clone` implements the `clone` method, which when implemented for the
-whole type, calls `clone` on each of the parts of the type. This means all the
-fields or values in the type must also implement `Clone` to derive `Clone`.
-
-An example of when `Clone` is required is when calling the `to_vec` method on a
-slice. The slice doesn’t own the type instances it contains, but the vector
-returned from `to_vec` will need to own its instances, so `to_vec` calls
-`clone` on each item. Thus, the type stored in the slice must implement `Clone`.
-
-The `Copy` trait allows you to duplicate a value by only copying bits stored on
-the stack; no arbitrary code is necessary. See the [“Stack-Only Data:
-Copy”][stack-only-data-copy] section in Chapter 4 for more
-information on `Copy`.
-
-The `Copy` trait doesn’t define any methods to prevent programmers from
-overloading those methods and violating the assumption that no arbitrary code
-is being run. That way, all programmers can assume that copying a value will be
-very fast.
-
-You can derive `Copy` on any type whose parts all implement `Copy`. A type that
-implements `Copy` must also implement `Clone`, because a type that implements
-`Copy` has a trivial implementation of `Clone` that performs the same task as
+## Apéndice C: Rasgos Derivables
+
+Apéndice C: Rasgos Derivables
+
+En varios lugares del libro, hemos hablado del atributo derive, que
+puede aplicarse a una definición de estructura o enumeración. El atributo derive genera
+código que implementará un rasgo con su propia implementación por defecto en el
+tipo que se ha anotado con la sintaxis `derive`.
+
+En este apéndice, proporcionamos una referencia de todos los rasgos en la biblioteca estándar
+que puede usar con `derive`. Cada sección cubre:
+
+* Qué operadores y métodos derivan este rasgo permitirán
+* Qué hace la implementación del rasgo proporcionada por `derive`
+* Qué significa implementar el rasgo sobre el tipo
+* Las condiciones en las que estás permitido o no permitido implementar el rasgo
+* Ejemplos de operaciones que requieren el rasgo
+
+Si deseas un comportamiento diferente al proporcionado por el atributo `derive`,
+consulta la documentación de la [biblioteca estándar](../std/index.html)
+para cada rasgo para obtener detalles de cómo implementarlos manualmente.
+
+El resto de los rasgos definidos en la biblioteca estándar no se pueden implementar en
+tus tipos usando `derive`. Estos rasgos no tienen un comportamiento por defecto sensato,
+así que depende de ti implementarlos de la manera que sea adecuada para lo que estás
+tratando de lograr.
+
+Un ejemplo de un rasgo que no se puede derivar es `Display`, que maneja la
+formateación para los usuarios finales. Siempre debes considerar la forma adecuada de
+mostrar un tipo a un usuario final. ¿Qué partes del tipo debería un usuario final ver?
+¿Qué partes les resultarían relevantes? ¿Qué formato de los datos sería más relevante
+para ellos? El compilador de Rust no tiene esta visión, por lo que
+no puede proporcionar un comportamiento por defecto adecuado para ti.
+
+La lista de rasgos derivables proporcionados en este apéndice no es exhaustiva:
+las bibliotecas pueden implementar `derive` para sus propios rasgos, haciendo que la lista de
+rasgos que puedes usar con `derive` sea verdaderamente abierta. Implementar `derive`
+implica usar una macro procedural, que se cubre en la
+[sección "Macros"][macros] del Capítulo 19.
+
+### `Debug` para salida de programador
+
+El parámetro `Debug` permite el formato de depuración en cadenas de formato, que indica añadiendo `:?` dentro de los marcadores `{}`.
+
+El parámetro `Debug` le permite imprimir instancias de un tipo para propósitos de depuración, de modo que usted y otros programadores que utilicen su tipo puedan inspeccionar una instancia en un punto específico de la ejecución de un programa.
+
+El parámetro `Debug` es necesario, por ejemplo, en el uso de la macro `assert_eq!`. Esta macro imprime los valores de las instancias dadas como argumentos si la aserción de igualdad falla, para que los programadores puedan ver por qué las dos instancias no eran iguales.
+
+
+### `PartialEq` y `Eq` para comparaciones de igualdad
+
+El parámetro `PartialEq` le permite comparar instancias de un tipo para comprobar la igualdad y permite el uso de los operadores `==` y `!=`.
+
+Derivando `PartialEq` implementa el método `eq`. Cuando `PartialEq` es derivado en estructuras, dos instancias son iguales solo si todos los campos son iguales y las instancias no son iguales si algún campo no es igual. Cuando se deriva en enums, cada variante es igual a sí misma y no es igual a las otras variantes.
+
+El parámetro `PartialEq` es requerido, por ejemplo, con el uso de la macro `assert_eq!`, que necesita ser capaz de comparar dos instancias de un tipo para la igualdad.
+
+El parámetro `Eq` no tiene métodos. Su propósito es señalar que para cada valor del tipo anotado, el valor es igual a sí mismo. El trait `Eq` solo se puede aplicar a tipos que también implementan `PartialEq`, aunque no todos los tipos que implementan `PartialEq` pueden implementar `Eq`. Un ejemplo de esto son los tipos de números con punto flotante: la implementación de los números con punto flotante establece que dos instancias del valor no es un número (`NaN`) no son iguales entre sí.
+
+Un ejemplo de cuando se requiere `Eq` es para las claves en un `HashMap` para que el `HashMap` pueda decir si dos claves son iguales.
+
+### `PartialOrd` y `Ord` para comparaciones de ordenación
+
+El parámetro `PartialOrd` le permite comparar instancias de un tipo con propósitos de ordenación.
+fines de ordenación. Un tipo que implemente `PartialOrd` puede usarse con los operadores `<`,`>`.
+operadores `<`,`>`, `<=` y `>=`. Sólo puedes aplicar el parámetro `PartialOrd` a tipos que también implementen `PartialOrd`.
+a tipos que también implementen `PartialEq`.
+
+La función `PartialOrd` implementa el método `partial_cmp`, que devuelve una `Option`.
+ordenación. Un ejemplo de un valor que no produce un ordenamiento, aunque la mayoría de los valores de ese tipo puedan
+la mayoría de los valores de ese tipo pueden compararse, es el valor de coma flotante
+no-un-número (`NaN`). Llame a `partial_cmp` con cualquier número flotante y
+el valor flotante `NaN` devolverá `None`.
+
+Cuando se han utilizado structs, `PartialOrd` compara dos instancias comparando
+el valor en cada campo en el orden en que los campos aparecen en la definición del struct.
+de la estructura. Cuando se derivan en enums, las variantes del enum declaradas anteriormente en la definición del enum son
+anteriores en la definición del enum se consideran menores que las variantes declaradas posteriormente.
+variantes enumeradas más tarde.
+
+El parámetro `PartialOrd` es necesario, por ejemplo, para el método `gen_range` de la crate `rand` que es necesario para el método `gen_range` de la crate `rand` de la caja `rand`, que genera un valor aleatorio en el rango especificado por una expresión `range`.
+
+El parámetro `Order` permite saber que para dos valores cualesquiera de tipo
+anotados, habrá un orden válido. El parámetro `Order` implementa el método `cmp`, que devuelve el método `cmp`.
+método `cmp`, que devuelve un `Ordering` en lugar de una `Option` porque
+siempre habrá una ordenación válida. Sólo se puede aplicar el parámetro `Ordering` a los tipos
+que también implementen `PartialOrd` y `Eq` (y `Eq` requiere `PartialEq`).
+Cuando se deriva en structs y enums, `cmp` se comporta de la misma manera que la implementación `partialOrder` de `partialEq`.
+la implementación derivada de `partial_cmp` con `PartialOrd`.
+
+Un ejemplo de cuando se requiere un `Ord` es cuando se almacenan valores en un
+`BTreeSet`, una estructura de datos que almacena datos basados en el orden de los valores.
+orden de clasificación de los valores.
+
+### `Clone` y `Copy` para Duplicar Valores.
+
+El parámetro Clone te permite crear explícitamente una copia profunda de un valor, y
+el proceso de duplicación puede involucrar ejecutar código arbitrario y copiar datos en la heap. Consulta la sección [“Formas en que las variables y los datos interactúan:
+Clonar”][ways-variables-and-data-interact-clone] section in
+en el Capítulo 4 para obtener más información sobre `Clone`.
+
+Derivar `Clone` implementa el método `clone`, que al implementarse para el
+tipo completo, llama a `clone` en cada una de las partes del tipo. Esto significa que todos los
+campos o valores en el tipo también deben implementar `Clone` para derivar `Clone`.
+
+Un ejemplo de cuándo se requiere `Clone` es al llamar al método `to_vec` en una
+porción. La porción no posee las instancias de tipo que contiene, pero el vector
+devuelto desde `to_vec` necesitará poseer sus instancias, por lo que `to_vec` llama
+`clone` en cada elemento. Por lo tanto, el tipo almacenado en la porción debe implementar `Clone`.
+
+El parámetro `Copy` te permite duplicar un valor copiando únicamente bits almacenados en
+la pila; no se requiere código arbitrario. Consulta la sección [“Datos solo en la pila:
+Copiar”][stack-only-data-copy] en el Capítulo 4 para obtener más
+información sobre `Copy`.
+
+Puedes usar el parámetro `Copy` en cualquier tipo cuyas partes implementen todas `Copy`. Un tipo que
+implementa `Copy` también debe implementar Clone, porque un tipo que implementa
+`Copy` tiene una implementación trivial de `Clone` que realiza la misma tarea que
`Copy`.
-The `Copy` trait is rarely required; types that implement `Copy` have
-optimizations available, meaning you don’t have to call `clone`, which makes
-the code more concise.
+El parámetro `Copy` se requiere raramente; los tipos que implementan `Copy` tienen
+optimizaciones disponibles, lo que significa que no tienes que llamar a `clone`, lo que hace
+que el código sea más conciso.
-Everything possible with `Copy` you can also accomplish with `Clone`, but the
-code might be slower or have to use `clone` in places.
+Todo lo posible con `Copy` también se puede lograr con `Clone`, pero el código puede ser más lento o tener que usar `clone` en algunos lugares.
-### `Hash` for Mapping a Value to a Value of Fixed Size
+### `Hash` para asignar un valor a un valor de tamaño fijo
-The `Hash` trait allows you to take an instance of a type of arbitrary size and
-map that instance to a value of fixed size using a hash function. Deriving
-`Hash` implements the `hash` method. The derived implementation of the `hash`
-method combines the result of calling `hash` on each of the parts of the type,
-meaning all fields or values must also implement `Hash` to derive `Hash`.
+El parámetro `Hash` permite tomar una instancia de un tipo de tamaño arbitrario y mapear esa instancia a un valor de tamaño fijo usando una función hash. La derivación de `Hash` implementa el método `hash`. La implementación derivada del método `hash` combina el resultado de llamar a hash en cada una de las partes del tipo, lo que significa que todos los campos o valores también deben implementar `Hash` para usar `Hash`.
-An example of when `Hash` is required is in storing keys in a `HashMap`
-to store data efficiently.
+Un ejemplo de cuándo se requiere `Hash` es al almacenar claves en un `HashMap` para almacenar datos de manera eficiente.
-### `Default` for Default Values
+### `Default` para valores por defecto
-The `Default` trait allows you to create a default value for a type. Deriving
-`Default` implements the `default` function. The derived implementation of the
-`default` function calls the `default` function on each part of the type,
-meaning all fields or values in the type must also implement `Default` to
-derive `Default`.
+El parametro `Default` permite crear un valor por defecto para un tipo. Derivando
+`Default` implementa la función `default`. La implementación derivada de la función
+llama a la función `default` en cada parte del tipo,
+es decir, todos los campos o valores del tipo deben implementar también la función `Default` para poder
+derivar `Default`.
-The `Default::default` function is commonly used in combination with the struct
-update syntax discussed in the [“Creating Instances From Other Instances With
-Struct Update
-Syntax”][creating-instances-from-other-instances-with-struct-update-syntax]
-section in Chapter 5. You can customize a few fields of a struct and then
-set and use a default value for the rest of the fields by using
-`..Default::default()`.
+La función `Default::default` se utiliza habitualmente en combinación con la sintaxis struct
+de la que se habla en la sección ["Creación de instancias a partir de otras instancias con
+actualización de estructuras
+Syntax"][creating-instances-from-other-instances-with-struct-update-syntax]
+en el Capítulo 5. Puede personalizar algunos campos de una estructura y luego
+establecer y utilizar un valor por defecto para el resto de los campos utilizando
+Default::default()`.
-The `Default` trait is required when you use the method `unwrap_or_default` on
-`Option` instances, for example. If the `Option` is `None`, the method
-`unwrap_or_default` will return the result of `Default::default` for the type
-`T` stored in the `Option`.
+El parametro `Default` es necesario cuando utilizas el método `unwrap_or_default` en instancias de `Option`.
+en instancias de `Option`, por ejemplo. Si la `Option` es `None`, el método
+`unwrap_or_default` devolverá el resultado de `Default::default` para el tipo
+`T` almacenado en la `Opción`.
[creating-instances-from-other-instances-with-struct-update-syntax]:
ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
diff --git a/src/appendix-04-useful-development-tools.md b/src/appendix-04-useful-development-tools.md
index 2909559af4..adf02f8b36 100644
--- a/src/appendix-04-useful-development-tools.md
+++ b/src/appendix-04-useful-development-tools.md
@@ -1,41 +1,41 @@
-## Appendix D - Useful Development Tools
+## Apéndice D - Herramientas útiles para el desarrollo
In this appendix, we talk about some useful development tools that the Rust
project provides. We’ll look at automatic formatting, quick ways to apply
warning fixes, a linter, and integrating with IDEs.
-### Automatic Formatting with `rustfmt`
+### Formateo automático con `rustfmt`
-The `rustfmt` tool reformats your code according to the community code style.
-Many collaborative projects use `rustfmt` to prevent arguments about which
-style to use when writing Rust: everyone formats their code using the tool.
+La herramienta `rustfmt` reformatea su código según el estilo de código de la comunidad.
+Muchos proyectos colaborativos utilizan `rustfmt` para evitar discusiones sobre qué
+estilo a utilizar cuando se escribe Rust: todo el mundo formatea su código utilizando la herramienta.
-To install `rustfmt`, enter the following:
+Para instalar `rustfmt`, introduzca lo siguiente:
```console
$ rustup component add rustfmt
```
-This command gives you `rustfmt` and `cargo-fmt`, similar to how Rust gives you
-both `rustc` and `cargo`. To format any Cargo project, enter the following:
+Este comando te da `rustfmt` y `cargo-fmt`, de forma similar a como Rust te da
+tanto `rustc` como `cargo`. Para formatear cualquier proyecto Cargo, introduzca lo siguiente:
```console
$ cargo fmt
```
-Running this command reformats all the Rust code in the current crate. This
-should only change the code style, not the code semantics. For more information
-on `rustfmt`, see [its documentation][rustfmt].
+La ejecución de este comando reformatea todo el código Rust en el crate actual. Este
+sólo debería cambiar el estilo del código, no la semántica del mismo. Para más información
+de `rustfmt`, ver [its documentation][rustfmt].
[rustfmt]: https://github.com/rust-lang/rustfmt
-### Fix Your Code with `rustfix`
+### Arregle su código con `rustfix`.
-The rustfix tool is included with Rust installations and can automatically fix
-some compiler warnings. If you’ve written code in Rust, you’ve probably seen
-compiler warnings. For example, consider this code:
+La herramienta rustfix se incluye con las instalaciones de Rust y puede corregir automáticamente
+algunas advertencias del compilador. Si ha escrito código en Rust, probablemente haya visto
+advertencias del compilador. Por ejemplo, considere este código:
-Filename: src/main.rs
+nombre de fichero: src/main.rs
```rust
fn do_something() {}
@@ -47,8 +47,8 @@ fn main() {
}
```
-Here, we’re calling the `do_something` function 100 times, but we never use the
-variable `i` in the body of the `for` loop. Rust warns us about that:
+Aquí, estamos llamando a la función `do_something` 100 veces, pero nunca usamos la variable
+variable `i` en el cuerpo del bucle `for`. Rust nos advierte de ello:
```console
$ cargo build
@@ -64,9 +64,9 @@ warning: unused variable: `i`
Finished dev [unoptimized + debuginfo] target(s) in 0.50s
```
-The warning suggests that we use `_i` as a name instead: the underscore
-indicates that we intend for this variable to be unused. We can automatically
-apply that suggestion using the `rustfix` tool by running the command `cargo
+La advertencia sugiere que utilicemos `_i` como nombre: el guión bajo
+indica que pretendemos que esta variable no se utilice. Podemos aplicar automáticamente
+aplicar esta sugerencia con la herramienta `rustfix` ejecutando el comando command `cargo
fix`:
```console
@@ -76,10 +76,10 @@ $ cargo fix
Finished dev [unoptimized + debuginfo] target(s) in 0.59s
```
-When we look at *src/main.rs* again, we’ll see that `cargo fix` has changed the
+Cuando miramos *src/main.rs* de nuevo, veremos que `cargo fix` ha cambiado el
code:
-Filename: src/main.rs
+nombre de fichero: src/main.rs
```rust
fn do_something() {}
@@ -91,42 +91,42 @@ fn main() {
}
```
-The `for` loop variable is now named `_i`, and the warning no longer appears.
+La variable del bucle `for` se llama ahora `_i`, y ya no aparece la advertencia.
-You can also use the `cargo fix` command to transition your code between
-different Rust editions. Editions are covered in Appendix E.
+También puedes usar el comando `cargo fix` para hacer la transición de tu código entre
+diferentes ediciones de Rust. Las ediciones están cubiertas en el Apéndice E.
-### More Lints with Clippy
+### Más Lints con Clippy
-The Clippy tool is a collection of lints to analyze your code so you can catch
-common mistakes and improve your Rust code.
+La herramienta Clippy es una colección de lints para analizar tu código y así poder detectar
+errores comunes y mejorar tu código Rust.
-To install Clippy, enter the following:
+Para instalar Clippy, introduzca lo siguiente:
```console
$ rustup component add clippy
```
-To run Clippy’s lints on any Cargo project, enter the following:
+Para ejecutar las lints de Clippy en cualquier proyecto de Cargo, introduzca lo siguiente:
```console
$ cargo clippy
```
-For example, say you write a program that uses an approximation of a
-mathematical constant, such as pi, as this program does:
+Por ejemplo, digamos que escribes un programa que utiliza una aproximación de una
+constante matemática, como pi, como hace este programa:
-Filename: src/main.rs
+nombre de fichero: src/main.rs
```rust
fn main() {
let x = 3.1415;
let r = 8.0;
- println!("the area of the circle is {}", x * r * r);
+ println!("el área del círculo es {}", x * r * r);
}
```
-Running `cargo clippy` on this project results in this error:
+La ejecución de `cargo clippy` en este proyecto da lugar a este error:
```text
error: approximate value of `f{32, 64}::consts::PI` found. Consider using it directly
@@ -139,10 +139,10 @@ error: approximate value of `f{32, 64}::consts::PI` found. Consider using it dir
= help: for further information visit https://rust-lang-nursery.github.io/rust-clippy/master/index.html#approx_constant
```
-This error lets you know that Rust has this constant defined more precisely and
-that your program would be more correct if you used the constant instead. You
-would then change your code to use the `PI` constant. The following code
-doesn’t result in any errors or warnings from Clippy:
+Este error le permite saber que Rust tiene esta constante definida con mayor precisión y
+que tu programa sería más correcto si usaras la constante en su lugar. Usted
+cambiaría su código para utilizar la constante `PI`. El siguiente código
+no da lugar a ningún error o advertencia de Clippy:
Filename: src/main.rs
@@ -150,34 +150,34 @@ doesn’t result in any errors or warnings from Clippy:
fn main() {
let x = std::f64::consts::PI;
let r = 8.0;
- println!("the area of the circle is {}", x * r * r);
+ println!("el área del círculo es {}", x * r * r);
}
```
-For more information on Clippy, see [its documentation][clippy].
+Para más información sobre Clippy, consulte [la documentación][clippy].
[clippy]: https://github.com/rust-lang/rust-clippy
-### IDE Integration Using the Rust Language Server
+### Integración del IDE mediante el servidor de lenguaje Rust
-To help IDE integration, the Rust project distributes the *Rust Language
-Server* (`rls`). This tool speaks the [Language Server
-Protocol][lsp], which is a specification for IDEs and programming
-languages to communicate with each other. Different clients can use the `rls`,
-such as [the Rust plug-in for Visual Studio Code][vscode].
+Para ayudar a la integración del IDE, el proyecto Rust distribuye el *Rust Language
+Server* (`rls`). Esta herramienta habla el [Language Server
+Protocolo][lsp],
+para comunicarse entre sí. Diferentes clientes pueden utilizar el `rls`,
+como por ejemplo [el plug-in de Rust para Visual Studio Code][vscode].
[lsp]: http://langserver.org/
[vscode]: https://marketplace.visualstudio.com/items?itemName=rust-lang.rust
-To install the `rls`, enter the following:
+Para instalar el `rls`, introduzca lo siguiente:
```console
$ rustup component add rls
```
-Then install the language server support in your particular IDE; you’ll gain
-abilities such as autocompletion, jump to definition, and inline errors.
+A continuación, instale el soporte para el servidor de lenguaje en su IDE particular; obtendrá
+habilidades como el autocompletado, el salto a la definición y los errores en línea.
-For more information on the `rls`, see [its documentation][rls].
+Para más información sobre el `rls`, véase [su documentación][rls].
[rls]: https://github.com/rust-lang/rls
diff --git a/src/appendix-05-editions.md b/src/appendix-05-editions.md
index db98ecc5ee..718f2e6c28 100644
--- a/src/appendix-05-editions.md
+++ b/src/appendix-05-editions.md
@@ -1,57 +1,55 @@
-## Appendix E - Editions
-
-In Chapter 1, you saw that `cargo new` adds a bit of metadata to your
-*Cargo.toml* file about an edition. This appendix talks about what that means!
-
-The Rust language and compiler have a six-week release cycle, meaning users get
-a constant stream of new features. Other programming languages release larger
-changes less often; Rust releases smaller updates more frequently. After a
-while, all of these tiny changes add up. But from release to release, it can be
-difficult to look back and say, “Wow, between Rust 1.10 and Rust 1.31, Rust has
-changed a lot!”
-
-Every two or three years, the Rust team produces a new Rust *edition*. Each
-edition brings together the features that have landed into a clear package with
-fully updated documentation and tooling. New editions ship as part of the usual
-six-week release process.
-
-Editions serve different purposes for different people:
-
-* For active Rust users, a new edition brings together incremental changes into
- an easy-to-understand package.
-* For non-users, a new edition signals that some major advancements have
- landed, which might make Rust worth another look.
-* For those developing Rust, a new edition provides a rallying point for the
- project as a whole.
-
-At the time of this writing, two Rust editions are available: Rust 2015 and
-Rust 2018. This book is written using Rust 2018 edition idioms.
-
-The `edition` key in *Cargo.toml* indicates which edition the compiler should
-use for your code. If the key doesn’t exist, Rust uses `2015` as the edition
-value for backward compatibility reasons.
-
-Each project can opt in to an edition other than the default 2015 edition.
-Editions can contain incompatible changes, such as including a new keyword that
-conflicts with identifiers in code. However, unless you opt in to those
-changes, your code will continue to compile even as you upgrade the Rust
-compiler version you use.
-
-All Rust compiler versions support any edition that existed prior to that
-compiler’s release, and they can link crates of any supported editions
-together. Edition changes only affect the way the compiler initially parses
-code. Therefore, if you’re using Rust 2015 and one of your dependencies uses
-Rust 2018, your project will compile and be able to use that dependency. The
-opposite situation, where your project uses Rust 2018 and a dependency uses
-Rust 2015, works as well.
-
-To be clear: most features will be available on all editions. Developers using
-any Rust edition will continue to see improvements as new stable releases are
-made. However, in some cases, mainly when new keywords are added, some new
-features might only be available in later editions. You will need to switch
-editions if you want to take advantage of such features.
-
-For more details, the [*Edition
-Guide*](https://doc.rust-lang.org/stable/edition-guide/) is a complete book
-about editions that enumerates the differences between editions and explains
-how to automatically upgrade your code to a new edition via `cargo fix`.
+## Apéndice E - Ediciones
+
+En el Capítulo 1, viste que `cargo new` añade un poco de metadatos a tu archivo
+*Cargo.toml* sobre una edición. Este apéndice habla de lo que eso significa.
+
+El lenguaje y el compilador de Rust tienen un ciclo de lanzamiento de seis semanas, lo que significa que los usuarios reciben
+un flujo constante de nuevas características. Otros lenguajes de programación lanzan cambios más grandes
+cambios más grandes con menos frecuencia; Rust lanza actualizaciones más pequeñas con más frecuencia. Después de un tiempo, todos estos pequeños cambios se suman. Pero de una versión a otra, puede ser
+puede ser difícil mirar atrás y decir: "¡Vaya, entre Rust 1.10 y Rust 1.31, Rust ha cambiado mucho!
+
+Cada dos o tres años, el equipo de Rust produce una nueva *edición* de Rust. Cada
+edición reúne las características que han aterrizado en un paquete claro con
+documentación y herramientas totalmente actualizadas. Las nuevas ediciones se envían como parte del habitual
+proceso de lanzamiento de seis semanas.
+
+Las ediciones sirven a diferentes propósitos para diferentes personas:
+
+* Para los usuarios activos de Rust, una nueva edición reúne los cambios incrementales en
+ un paquete fácil de entender.
+* Para los no usuarios, una nueva edición indica que han llegado algunos avances importantes
+ que puede hacer que merezca la pena volver a mirar a Rust.
+* Para quienes desarrollan Rust, una nueva edición proporciona un punto de encuentro para el
+ proyecto en su conjunto.
+
+En el momento de escribir este artículo, hay dos ediciones de Rust disponibles: Rust 2015 y
+Rust 2018. Este libro está escrito utilizando los modismos de la edición Rust 2018.
+
+La clave `edición` en *Cargo.toml* indica la edición que el compilador debe
+utilizar para su código. Si la clave no existe, Rust utiliza `2015` como valor de edición
+por razones de compatibilidad.
+
+Cada proyecto puede optar por una edición distinta de la edición por defecto de 2015.
+Las ediciones pueden contener cambios incompatibles, como la inclusión de una nueva palabra clave que
+entra en conflicto con los identificadores en el código. Sin embargo, a menos que opte por esos
+cambios, su código continuará compilando aunque actualice la versión del compilador de Rust
+que utilices.
+
+Todas las versiones del compilador de Rust soportan cualquier edición que exista antes de ese
+compilador, y pueden enlazar crates de cualquier edición soportada
+soportadas. Los cambios de edición sólo afectan a la forma en que el compilador analiza inicialmente el código.
+código. Por lo tanto, si estás usando Rust 2015 y una de tus dependencias usa
+Rust 2018, tu proyecto compilará y podrá utilizar esa dependencia. La situación
+situación opuesta, en la que tu proyecto utiliza Rust 2018 y una dependencia utiliza
+Rust 2015, también funciona.
+
+Para ser claros: la mayoría de las funciones estarán disponibles en todas las ediciones. Los desarrolladores que utilicen
+cualquier edición de Rust seguirán viendo mejoras a medida que se realicen nuevas versiones estables
+se realicen. Sin embargo, en algunos casos, principalmente cuando se añaden nuevas palabras clave, algunas nuevas
+nuevas características podrían estar disponibles sólo en ediciones posteriores. Tendrá que cambiar de
+ediciones si quieres aprovechar estas características.
+
+Para más detalles, la [*Edición
+Guide*](https://doc.rust-lang.org/stable/edition-guide/) es un libro completo
+sobre ediciones que enumera las diferencias entre ediciones y explica
+cómo actualizar automáticamente tu código a una nueva edición mediante `cargo fix`.
diff --git a/src/appendix-06-translation.md b/src/appendix-06-translation.md
index cbd39743c9..704e00e637 100644
--- a/src/appendix-06-translation.md
+++ b/src/appendix-06-translation.md
@@ -1,7 +1,7 @@
-## Appendix F: Translations of the Book
+## Apéndice F: Traducciones del Libro
-For resources in languages other than English. Most are still in progress; see
-[the Translations label][label] to help or let us know about a new translation!
+Para recursos en idiomas distintos del inglés. La mayoría están todavía en proceso; vea
+[la etiqueta Traducciones][label] para ayudar o avisarnos de una nueva traducción.
[label]: https://github.com/rust-lang/book/issues?q=is%3Aopen+is%3Aissue+label%3ATranslations
diff --git a/src/appendix-07-nightly-rust.md b/src/appendix-07-nightly-rust.md
index 46e619c815..bde5f24d08 100644
--- a/src/appendix-07-nightly-rust.md
+++ b/src/appendix-07-nightly-rust.md
@@ -1,153 +1,166 @@
-## Appendix G - How Rust is Made and “Nightly Rust”
+## Apéndice G - Cómo está hecho Rust y "Rust nocturno"
-This appendix is about how Rust is made and how that affects you as a Rust
-developer.
+Este apéndice trata sobre cómo Rust está hecho y cómo esto te afecta como
+un desarrollador de Rust
-### Stability Without Stagnation
+### Estabilidad sin estancamiento
-As a language, Rust cares a *lot* about the stability of your code. We want
-Rust to be a rock-solid foundation you can build on, and if things were
-constantly changing, that would be impossible. At the same time, if we can’t
-experiment with new features, we may not find out important flaws until after
-their release, when we can no longer change things.
+Cómo lenguaje, a Rust le importa *mucho* la estabilidad de tu código. Queremos
+que Rust sea cual cimientos sólidos cómo la roca sobre los que tu puedas construir,
+y si las cosas estuvieran cambiando constantemente, sería imposible.
+Al mismo tiempo, si no podemos experimentar con características nuevas, no
+podríamos encontrar deficiencias importantes hasta su lanzamiento, cuando
+ya no podemos arreglar nada.
-Our solution to this problem is what we call “stability without stagnation”,
-and our guiding principle is this: you should never have to fear upgrading to a
-new version of stable Rust. Each upgrade should be painless, but should also
-bring you new features, fewer bugs, and faster compile times.
+Nuestra solución a este problema es lo que llamamos "estabilidad sin estancamiento",
+y el principio que nos guía es este: nunca deberías tener miedo a actualizar a una
+nueva versión estable de Rust. Cada actualización debería venir sin dolores
+de cabeza, pero al mismo tiempo traerte nuevas características, menos errores
+y tiempos de compilación más rápidos.
-### Choo, Choo! Release Channels and Riding the Trains
+### ¡Chu, Chu! Canales de lanzamiento y montando los trenes
-Rust development operates on a *train schedule*. That is, all development is
-done on the `master` branch of the Rust repository. Releases follow a software
-release train model, which has been used by Cisco IOS and other software
-projects. There are three *release channels* for Rust:
+El desarrollo de Rust opera en un *horario ferroviario*. Esto siendo, que todo
+el desarrollo se lleva cabo en la rama `master` del repositorio de Rust. Los
+lanzamientos siguen un modelo ferroviario para lanzamiento de software, que ha
+sido utilizado para Cisco IOS y otros proyectos de software. Hay tres *canales de lanzamiento*
+para Rust:
-* Nightly
+* Nocturno
* Beta
-* Stable
-
-Most Rust developers primarily use the stable channel, but those who want to
-try out experimental new features may use nightly or beta.
-
-Here’s an example of how the development and release process works: let’s
-assume that the Rust team is working on the release of Rust 1.5. That release
-happened in December of 2015, but it will provide us with realistic version
-numbers. A new feature is added to Rust: a new commit lands on the `master`
-branch. Each night, a new nightly version of Rust is produced. Every day is a
-release day, and these releases are created by our release infrastructure
+* Estable
+
+La mayoría de desarrolladores de Rust usan principalmente el canal estable, pero
+los que quieran probar nuevas características experimentales pueden usar
+nocturno o beta.
+
+Aquí hay un ejemplo de que cómo funciona el proceso de desarrollo y lanzamiento:
+vamos a asumir que el equipo de Rust está trabajando en el lanzamiento de Rust 1.5.
+Este lanzamiento ocurrió en Diciembre de 2015, pero no dará con números de
+versión realistas. Una nueva caractarística se añade a Rust: un nuevo commit
+cae en la rama `master`. Cada noche, una nueva versión de Rust nocturno es
+producida. Cada día es una día de lanzamiento, y estos lanzamientos son
+creados por nuestra infraestructura automáticamente. Así que según pasa el
+tiempo, nuestros lanzamientos tienen esta pinta, una vez por noche:
automatically. So as time passes, our releases look like this, once a night:
```text
-nightly: * - - * - - *
+nocturno: * - - * - - *
```
-Every six weeks, it’s time to prepare a new release! The `beta` branch of the
-Rust repository branches off from the `master` branch used by nightly. Now,
-there are two releases:
+Cada seis semanas, ¡es hora de preparar un nuevo lanzamiento! La rama `beta`
+del repositorio de Rust se escinde de la rama `master` utilizada para nocturno.
+Ahora hay dos lanzamientos:
```text
-nightly: * - - * - - *
- |
-beta: *
+nocturno: * - - * - - *
+ |
+beta: *
```
-Most Rust users do not use beta releases actively, but test against beta in
-their CI system to help Rust discover possible regressions. In the meantime,
-there’s still a nightly release every night:
+La mayoría de los usuarios de Rust no utilizan las versiones beta activamente,
+pero prueban con estas sus sistemas de CI (Continous Integration, en español,
+Integración Continua) para ayudar a Rust a descubrir posibles deficiencias.
+Mientras tanto, sigue habiendo un nuevo lanzamiento de Rust nocturno cada noche:
```text
-nightly: * - - * - - * - - * - - *
- |
-beta: *
+nocturno: * - - * - - * - - * - - *
+ |
+beta: *
```
-Let’s say a regression is found. Good thing we had some time to test the beta
-release before the regression snuck into a stable release! The fix is applied
-to `master`, so that nightly is fixed, and then the fix is backported to the
-`beta` branch, and a new release of beta is produced:
+Digamos que se ha encontrado una deficiencia. ¡Que bien que hallamos tenido
+algo de tiempo antes de que se haya colado en el lanzamiento estable! El parche
+se aplica a `master`, para que la versión nocturna quede arreglada, y el parche
+respalde a la rama `beta`, y una nueva versión beta se produce:
```text
-nightly: * - - * - - * - - * - - * - - *
- |
-beta: * - - - - - - - - *
+nocturno: * - - * - - * - - * - - * - - *
+ |
+beta: * - - - - - - - - *
```
-Six weeks after the first beta was created, it’s time for a stable release! The
-`stable` branch is produced from the `beta` branch:
+Seis semanas tras la creación de la primera beta, ¡es hora de un lanzamiento
+estable! La rama `stable` se crea desde la rama `beta`:
```text
-nightly: * - - * - - * - - * - - * - - * - * - *
- |
-beta: * - - - - - - - - *
- |
-stable: *
+nocturno: * - - * - - * - - * - - * - - * - * - *
+ |
+beta: * - - - - - - - - *
+ |
+estable: *
```
-Hooray! Rust 1.5 is done! However, we’ve forgotten one thing: because the six
-weeks have gone by, we also need a new beta of the *next* version of Rust, 1.6.
-So after `stable` branches off of `beta`, the next version of `beta` branches
-off of `nightly` again:
+¡Hurra! ¡Rust 1.5 está creado! Sin embargo, nos hemos olvidado una cosa: cómo
+han pasado seis semanas, necesitamos una nueva beta para la *siguiente* versión
+de Rust, 1.6. Así que tras la escisión de `stable` desde `beta`, la siguiente
+versión de `beta` se escinde de `master`:
```text
-nightly: * - - * - - * - - * - - * - - * - * - *
- | |
-beta: * - - - - - - - - * *
- |
-stable: *
+nocturno: * - - * - - * - - * - - * - - * - * - *
+ | |
+beta: * - - - - - - - - * *
+ |
+estable: *
```
-This is called the “train model” because every six weeks, a release “leaves the
-station”, but still has to take a journey through the beta channel before it
-arrives as a stable release.
-
-Rust releases every six weeks, like clockwork. If you know the date of one Rust
-release, you can know the date of the next one: it’s six weeks later. A nice
-aspect of having releases scheduled every six weeks is that the next train is
-coming soon. If a feature happens to miss a particular release, there’s no need
-to worry: another one is happening in a short time! This helps reduce pressure
-to sneak possibly unpolished features in close to the release deadline.
-
-Thanks to this process, you can always check out the next build of Rust and
-verify for yourself that it’s easy to upgrade to: if a beta release doesn’t
-work as expected, you can report it to the team and get it fixed before the
-next stable release happens! Breakage in a beta release is relatively rare, but
-`rustc` is still a piece of software, and bugs do exist.
-
-### Unstable Features
-
-There’s one more catch with this release model: unstable features. Rust uses a
-technique called “feature flags” to determine what features are enabled in a
-given release. If a new feature is under active development, it lands on
-`master`, and therefore, in nightly, but behind a *feature flag*. If you, as a
-user, wish to try out the work-in-progress feature, you can, but you must be
-using a nightly release of Rust and annotate your source code with the
-appropriate flag to opt in.
-
-If you’re using a beta or stable release of Rust, you can’t use any feature
-flags. This is the key that allows us to get practical use with new features
-before we declare them stable forever. Those who wish to opt into the bleeding
-edge can do so, and those who want a rock-solid experience can stick with
-stable and know that their code won’t break. Stability without stagnation.
-
-This book only contains information about stable features, as in-progress
-features are still changing, and surely they’ll be different between when this
-book was written and when they get enabled in stable builds. You can find
-documentation for nightly-only features online.
-
-### Rustup and the Role of Rust Nightly
-
-Rustup makes it easy to change between different release channels of Rust, on a
-global or per-project basis. By default, you’ll have stable Rust installed. To
-install nightly, for example:
+
+Esto se llama "modelo ferroviario" porque cada seis semanas, una versión "parte
+de la estación", pero todavía tiene que hacer un viaje a través del canal beta
+antes de llegar al lanzamiento estable.
+
+Rust lanza cada seis semanas, cómo un reloj. Si sabes la fecha de lanzamiento de
+uno de los lanzamientos de Rust, puedes conocer el siguiente: seis semanas después.
+Un aspecto chulo de tener un lanzamiento cada seis semanas es que el siguiente tren
+va a venir pronto. Si una característica se pierde un lanzamiento en concreto, no hay
+necesidad de preocuparse: ¡va a haber una nueva en poco tiempo! Esto ayuda a
+reducir la presión de introducir una característica sin pulir cerca de la fecha
+de lanzamiento.
+
+Gracias a este proceso, siempre puedes comprobar la siguiente versión de Rust
+y comprobar por tí mismo lo fácil que es actualizar: ¡si una beta no funciona
+cómo se espera de ella, puedes avisar al equipo de Rust y que quede reparada
+para el siguiente lanzamiento estable! Una rotura en una versión beta es
+bastante extraño, pero `rustc` sigue siendo software, y los bugs seguirán
+existiendo.
+
+### Características inestables
+
+Hay una cosa más con este tiempo de modelo de lanzamiento: características
+inestables. Rust usa una técnica llamada "banderas de características" para
+determinar que características estarán activadas en un lanzamiento en concreto.
+Si una nueva característica está bajo desarrollo activo, cae en `master`, y por
+lo tanto, en nocturno, pero detrás de una *bandera de característica*. Si tú,
+cómo usuario, quieres probar una de las características en desarrollo, puedes,
+pero deber usar la versión nocturna correspondiente e indicar tu código fuente
+con la bandera apropiada para poder optar a utilizarla.
+
+Si estas utilizando una versión beta o estable de Rust, no puedes utilizar
+característica bandera. Esta es la clave que nos permite conseguir uso práctico
+antes de declararlas estables para siempre. Aquellos que quieran optar en
+la vanguardia pueden hacerlo, y aquellos que quieran una experiencia sólida
+cómo la roca pueden quedarse cón la versión estable y saber que su código no
+se romperá. Estabilidad sin estancamiento.
+
+Este libro solo contiene información sobre las características estables,
+cómo las características en progreso todavía están cambiando, y seguramente
+serán distintas desde que están escritas en este libro y son habilitadas
+en las versiones estables. Puedes encontrar documentación para las
+características exclusivas de las versiones nocturnas online.
+
+### Rustup y el papel de Rust nocturno
+
+Rustup hace que sea sencillo cambiar entre diferentes canales de lanzamiento de,
+Rust, de manera global o por proyecto. Por defecto, tendrás Rust estable instalado.
+Para instalar nocturno, por ejemplo:
```console
$ rustup toolchain install nightly
```
-You can see all of the *toolchains* (releases of Rust and associated
-components) you have installed with `rustup` as well. Here’s an example on one
-of your authors’ Windows computer:
+También puedes ver todas las *cadena de herramientas* (lanzamientos de Rust y
+componenetes asociados) que tienes instaladas con `rustup`. Aquí hay un ejemplo
+en uno de los PC con Windows de uno de los autores:
```powershell
> rustup toolchain list
@@ -156,46 +169,54 @@ beta-x86_64-pc-windows-msvc
nightly-x86_64-pc-windows-msvc
```
-As you can see, the stable toolchain is the default. Most Rust users use stable
-most of the time. You might want to use stable most of the time, but use
-nightly on a specific project, because you care about a cutting-edge feature.
-To do so, you can use `rustup override` in that project’s directory to set the
-nightly toolchain as the one `rustup` should use when you’re in that directory:
+Cómo puedes ver, la cadena de herramientas estable es la opción por defecto. La
+mayoría de los usuarios de Rust usan la versión estable la mayoría del tiempo.
+Puede que quieras utilizar la versión estable la mayor parte del tiempo, pero
+quieres utilizar la versión nocturna para un proyecto en específico porque
+necesitas una de las características pioneras de dicha versión. Para ello, puedes
+usar `rustup override` en el directorio del proyecto para establecer la cadena
+de herramientas nocturna como la opción que `rustup` debe utilizar cuando estés
+en ese directorio en concreto:
```console
-$ cd ~/projects/needs-nightly
+$ cd ~/proyectos/necesita-nocturno
$ rustup override set nightly
```
-Now, every time you call `rustc` or `cargo` inside of
-*~/projects/needs-nightly*, `rustup` will make sure that you are using nightly
-Rust, rather than your default of stable Rust. This comes in handy when you
-have a lot of Rust projects!
-
-### The RFC Process and Teams
-
-So how do you learn about these new features? Rust’s development model follows
-a *Request For Comments (RFC) process*. If you’d like an improvement in Rust,
-you can write up a proposal, called an RFC.
-
-Anyone can write RFCs to improve Rust, and the proposals are reviewed and
-discussed by the Rust team, which is comprised of many topic subteams. There’s
-a full list of the teams [on Rust’s
-website](https://www.rust-lang.org/governance), which includes teams for
-each area of the project: language design, compiler implementation,
-infrastructure, documentation, and more. The appropriate team reads the
-proposal and the comments, writes some comments of their own, and eventually,
-there’s consensus to accept or reject the feature.
-
-If the feature is accepted, an issue is opened on the Rust repository, and
-someone can implement it. The person who implements it very well may not be the
-person who proposed the feature in the first place! When the implementation is
-ready, it lands on the `master` branch behind a feature gate, as we discussed
-in the [“Unstable Features”](#unstable-features) section.
-
-After some time, once Rust developers who use nightly releases have been able
-to try out the new feature, team members will discuss the feature, how it’s
-worked out on nightly, and decide if it should make it into stable Rust or not.
-If the decision is to move forward, the feature gate is removed, and the
-feature is now considered stable! It rides the trains into a new stable release
-of Rust.
+Ahora, cada vez que invoques `rustc` o `cargo` dentro de *~/proyectos/necesita-nocturno*,
+`rustup` se asegurará de que estés utilizando Rust nocturno, en vez de la
+versión estable por defecto de Rust. ¡Esto es muy útil cuándo tienes muchos proyectos
+en Rust!
+
+### El proceso RFC y equipos
+
+¿Cómo puedes aprender sobre estas nuevas características? El modelo de desarrollo
+de Rust sigue un
+*proceso de Solicitud De Comentarios (Requesto for Comments, en ingles, RFC)*.
+Si te gustaría una mejora en Rust, puedes escribir una proposición, llamada
+RFC.
+
+Cualquiera puede escribir RFCs para mejorar Rust, y estas proposiciones
+son revisadas y discutidas por el equipo de Rusts, el cuál está dividido
+por tópicos en subequipos. Hay una lista completa de los equipos
+[en la página web de Rust](https://www.rust-lang.org/es/governance),
+el cuál incluye equipos para cada área del proyecto: diseño de lenguaje,
+implementación del compilador, infraestructura, documentación y más. El
+equipo correspondiente lee la proposición y los comentarios, escribe sus
+propios comentarios, y al final, hay un consenso sobre si aceptar o rechazar
+la característica.
+
+Si la característica es aceptada, se abre un asunto en el repositorio de Rust,
+y alguien puede implementarlo. ¡La persona que mejor lo implemente, es probable que
+no sea la misma que propuso la característica en primer lugar! Cuando la
+implementación esté lista, cae en la rama `master` detrás de una bandera de
+característica, cómo ya comentamos en la sección
+["Características inestables"](#características-inestables).
+
+Después de algún tiempo, cuándo los desarrolladores de Rust que utilizan los
+lanzamientos nocturnos pueden probar la nueva característica, los miembros del
+equipo discutirán sobre la característica, y cómo ha funcionado en la versión
+nocturna, y decidir si debería pasar a Rust estable o no. Si la decisión es
+seguir adelante, se quita la bandera de característica, ¡y la característica
+ya se considera estable! Se monta en el tren hacia un nuevo lanzamiento de
+Rust estable.
\ No newline at end of file
diff --git a/src/ch00-00-introduction.md b/src/ch00-00-introduction.md
index c3d7c4a6e5..df44235057 100644
--- a/src/ch00-00-introduction.md
+++ b/src/ch00-00-introduction.md
@@ -1,191 +1,186 @@
-# Introduction
+# Introducción
-> Note: This edition of the book is the same as [The Rust Programming
-> Language][nsprust] available in print and ebook format from [No Starch
+>Nota: Esta edición del libro es la misma que [The Rust Programming
+> Languaje][nsprust] disponible en formato impreso y ebook de [No Starch
> Press][nsp].
[nsprust]: https://nostarch.com/rust
[nsp]: https://nostarch.com/
-Welcome to *The Rust Programming Language*, an introductory book about Rust.
-The Rust programming language helps you write faster, more reliable software.
-High-level ergonomics and low-level control are often at odds in programming
-language design; Rust challenges that conflict. Through balancing powerful
-technical capacity and a great developer experience, Rust gives you the option
-to control low-level details (such as memory usage) without all the hassle
-traditionally associated with such control.
-
-## Who Rust Is For
-
-Rust is ideal for many people for a variety of reasons. Let’s look at a few of
-the most important groups.
-
-### Teams of Developers
-
-Rust is proving to be a productive tool for collaborating among large teams of
-developers with varying levels of systems programming knowledge. Low-level code
-is prone to a variety of subtle bugs, which in most other languages can be
-caught only through extensive testing and careful code review by experienced
-developers. In Rust, the compiler plays a gatekeeper role by refusing to
-compile code with these elusive bugs, including concurrency bugs. By working
-alongside the compiler, the team can spend their time focusing on the program’s
-logic rather than chasing down bugs.
-
-Rust also brings contemporary developer tools to the systems programming world:
-
-* Cargo, the included dependency manager and build tool, makes adding,
- compiling, and managing dependencies painless and consistent across the Rust
- ecosystem.
-* Rustfmt ensures a consistent coding style across developers.
-* The Rust Language Server powers Integrated Development Environment (IDE)
- integration for code completion and inline error messages.
-
-By using these and other tools in the Rust ecosystem, developers can be
-productive while writing systems-level code.
-
-### Students
-
-Rust is for students and those who are interested in learning about systems
-concepts. Using Rust, many people have learned about topics like operating
-systems development. The community is very welcoming and happy to answer
-student questions. Through efforts such as this book, the Rust teams want to
-make systems concepts more accessible to more people, especially those new to
-programming.
-
-### Companies
-
-Hundreds of companies, large and small, use Rust in production for a variety of
-tasks. Those tasks include command line tools, web services, DevOps tooling,
-embedded devices, audio and video analysis and transcoding, cryptocurrencies,
-bioinformatics, search engines, Internet of Things applications, machine
-learning, and even major parts of the Firefox web browser.
-
-### Open Source Developers
-
-Rust is for people who want to build the Rust programming language, community,
-developer tools, and libraries. We’d love to have you contribute to the Rust
-language.
-
-### People Who Value Speed and Stability
-
-Rust is for people who crave speed and stability in a language. By speed, we
-mean the speed of the programs that you can create with Rust and the speed at
-which Rust lets you write them. The Rust compiler’s checks ensure stability
-through feature additions and refactoring. This is in contrast to the brittle
-legacy code in languages without these checks, which developers are often
-afraid to modify. By striving for zero-cost abstractions, higher-level features
-that compile to lower-level code as fast as code written manually, Rust
-endeavors to make safe code be fast code as well.
-
-The Rust language hopes to support many other users as well; those mentioned
-here are merely some of the biggest stakeholders. Overall, Rust’s greatest
-ambition is to eliminate the trade-offs that programmers have accepted for
-decades by providing safety *and* productivity, speed *and* ergonomics. Give
-Rust a try and see if its choices work for you.
-
-## Who This Book Is For
-
-This book assumes that you’ve written code in another programming language but
-doesn’t make any assumptions about which one. We’ve tried to make the material
-broadly accessible to those from a wide variety of programming backgrounds. We
-don’t spend a lot of time talking about what programming *is* or how to think
-about it. If you’re entirely new to programming, you would be better served by
-reading a book that specifically provides an introduction to programming.
-
-## How to Use This Book
-
-In general, this book assumes that you’re reading it in sequence from front to
-back. Later chapters build on concepts in earlier chapters, and earlier
-chapters might not delve into details on a topic; we typically revisit the
-topic in a later chapter.
-
-You’ll find two kinds of chapters in this book: concept chapters and project
-chapters. In concept chapters, you’ll learn about an aspect of Rust. In project
-chapters, we’ll build small programs together, applying what you’ve learned so
-far. Chapters 2, 12, and 20 are project chapters; the rest are concept chapters.
-
-Chapter 1 explains how to install Rust, how to write a “Hello, world!” program,
-and how to use Cargo, Rust’s package manager and build tool. Chapter 2 is a
-hands-on introduction to the Rust language. Here we cover concepts at a high
-level, and later chapters will provide additional detail. If you want to get
-your hands dirty right away, Chapter 2 is the place for that. At first, you
-might even want to skip Chapter 3, which covers Rust features similar to those
-of other programming languages, and head straight to Chapter 4 to learn about
-Rust’s ownership system. However, if you’re a particularly meticulous learner
-who prefers to learn every detail before moving on to the next, you might want
-to skip Chapter 2 and go straight to Chapter 3, returning to Chapter 2 when
-you’d like to work on a project applying the details you’ve learned.
-
-Chapter 5 discusses structs and methods, and Chapter 6 covers enums, `match`
-expressions, and the `if let` control flow construct. You’ll use structs and
-enums to make custom types in Rust.
-
-In Chapter 7, you’ll learn about Rust’s module system and about privacy rules
-for organizing your code and its public Application Programming Interface
-(API). Chapter 8 discusses some common collection data structures that the
-standard library provides, such as vectors, strings, and hash maps. Chapter 9
-explores Rust’s error-handling philosophy and techniques.
-
-Chapter 10 digs into generics, traits, and lifetimes, which give you the power
-to define code that applies to multiple types. Chapter 11 is all about testing,
-which even with Rust’s safety guarantees is necessary to ensure your program’s
-logic is correct. In Chapter 12, we’ll build our own implementation of a subset
-of functionality from the `grep` command line tool that searches for text
-within files. For this, we’ll use many of the concepts we discussed in the
-previous chapters.
-
-Chapter 13 explores closures and iterators: features of Rust that come from
-functional programming languages. In Chapter 14, we’ll examine Cargo in more
-depth and talk about best practices for sharing your libraries with others.
-Chapter 15 discusses smart pointers that the standard library provides and the
-traits that enable their functionality.
-
-In Chapter 16, we’ll walk through different models of concurrent programming
-and talk about how Rust helps you to program in multiple threads fearlessly.
-Chapter 17 looks at how Rust idioms compare to object-oriented programming
-principles you might be familiar with.
-
-Chapter 18 is a reference on patterns and pattern matching, which are powerful
-ways of expressing ideas throughout Rust programs. Chapter 19 contains a
-smorgasbord of advanced topics of interest, including unsafe Rust, macros, and
-more about lifetimes, traits, types, functions, and closures.
-
-In Chapter 20, we’ll complete a project in which we’ll implement a low-level
-multithreaded web server!
-
-Finally, some appendices contain useful information about the language in a
-more reference-like format. Appendix A covers Rust’s keywords, Appendix B
-covers Rust’s operators and symbols, Appendix C covers derivable traits
-provided by the standard library, Appendix D covers some useful development
-tools, and Appendix E explains Rust editions.
-
-There is no wrong way to read this book: if you want to skip ahead, go for it!
-You might have to jump back to earlier chapters if you experience any
-confusion. But do whatever works for you.
+Bienvenido a *El lenguaje de programación Rust*, un libro de introducción a Rust.
+El lenguaje de programación Rust le ayuda a escribir un software más rápido y fiable.
+La flexibilidad de alto nivel y el control de bajo nivel están a menudo en conflicto en el
+diseño de lenguajes de programación; Rust desafía ese conflicto. Mediante el equilibrio entre una potente
+capacidad técnica y una gran experiencia para el desarrollador, Rust te da la opción
+de controlar los detalles de bajo nivel (como el uso de la memoria) sin todas las molestias
+tradicionalmente asociados a dicho control.
+
+## Para quién es Rust
+
+Rust es ideal para muchas personas por diversas razones. Veamos algunos de
+los grupos más importantes.
+
+### Equipos de desarrollo
+
+Rust está demostrando ser una herramienta productiva para la colaboración entre grandes equipos de
+desarrolladores con distintos niveles de conocimiento de programación de sistemas. El código de bajo nivel
+es propenso a una variedad de errores sutiles, que en la mayoría de los otros lenguajes pueden ser
+en la mayoría de los otros lenguajes sólo se pueden detectar mediante pruebas exhaustivas y una cuidadosa revisión del código por parte de desarrolladores experimentados.
+experimentados. En Rust, el compilador desempeña un papel de guardián al negarse a
+compilar código con estos errores escurridizos, incluidos los de concurrencia. Al trabajar
+trabajando junto al compilador, el equipo puede dedicar su tiempo a centrarse en la lógica del programa
+lógica del programa en lugar de perseguir errores.
+
+Rust también aporta herramientas de desarrollo contemporáneas al mundo de la programación de sistemas:
+
+* Cargo, el gestor de dependencias y la herramienta de compilación incluidos, hace que añadir,
+ compilar y gestionar las dependencias de forma sencilla y coherente en todo el ecosistema de Rust.
+* Rustfmt garantiza un estilo de codificación coherente entre los desarrolladores.
+* El Servidor de Lenguaje Rust permite la integración del Entorno de Desarrollo Integrado (IDE)
+ para la finalización del código y los mensajes de error en línea.
+
+Utilizando estas y otras herramientas del ecosistema Rust, los desarrolladores pueden ser
+productivos mientras escriben código a nivel de sistemas.
+
+### Estudiantes
+
+Rust se dirige a los estudiantes y a los interesados en aprender los conceptos de los sistemas
+conceptos. Usando Rust, mucha gente ha aprendido sobre temas como el desarrollo de
+desarrollo de sistemas operativos. La comunidad es muy acogedora y está dispuesta a responder
+preguntas de los estudiantes. A través de esfuerzos como este libro, los equipos de Rust quieren
+hacer que los conceptos de sistemas sean más accesibles para más gente, especialmente para los nuevos en
+programación.
+
+### Empresas
+
+Cientos de empresas, grandes y pequeñas, utilizan Rust en la producción para una variedad de
+tareas. Esas tareas incluyen herramientas de línea de comandos, servicios web, herramientas DevOps
+dispositivos integrados, análisis y transcodificación de audio y vídeo, criptomonedas,
+bioinformática, motores de búsqueda, aplicaciones del Internet de las Cosas, aprendizaje
+aprendizaje automático, e incluso partes importantes del navegador web Firefox.
+
+### Desarrolladores de código abierto
+
+Rust es para la gente que quier construir en el lenguaje de programación Rust, la comunidad
+herramientas para desarrolladores y bibliotecas. Nos encantaría que contribuyeras al lenguaje Rust
+
+### Personas que valoran la rapidez y la estabilidad
+
+Rust es para la gente que anhela velocidad y estabilidad en un lenguaje. Por velocidad, nos referimos a
+nos referimos a la velocidad de los programas que puedes crear con Rust y a la velocidad a la que
+Rust te permite escribirlos. Los controles del compilador de Rust aseguran la estabilidad
+a través de la adición de características y la refactorización. Esto contrasta con el frágil
+código heredado en lenguajes sin estas comprobaciones, que los desarrolladores a menudo
+los desarrolladores suelen tener miedo de modificar. Al esforzarse por conseguir abstracciones de coste cero, las características de nivel superior
+de alto nivel que compilan en código de bajo nivel tan rápido como el código escrito manualmente, Rust
+se esfuerza por hacer que el código seguro sea también código rápido.
+
+El lenguaje Rust también espera dar soporte a muchos otros usuarios; los mencionados
+aquí son sólo algunos de los principales interesados. En general, la mayor ambición de Rust
+de Rust es eliminar las compensaciones que los programadores han aceptado durante
+décadas proporcionando seguridad *y* productividad, velocidad *y* ergonomía. Pruebe
+Rust y comprueba si sus opciones te sirven.
+
+## A quién va dirigido este libro
+
+Este libro asume que usted ha escrito código en otro lenguaje de programación pero
+no hace ninguna suposición sobre cuál. Hemos tratado de hacer el material
+ampliamente accesible para aquellos con una amplia variedad de antecedentes de programación. En
+No dedicamos mucho tiempo a hablar de lo que es la programación o de cómo pensar en ella.
+sobre ella. Si es completamente nuevo en la programación, le convendría
+leer un libro que proporcione específicamente una introducción a la programación.
+
+## Cómo usar este libro
+
+En general, este libro supone que se lee en secuencia de adelante hacia
+atrás. Los capítulos posteriores se basan en los conceptos de los anteriores, y los primeros
+capítulos anteriores, y es posible que no se profundice en los detalles de un tema; normalmente
+tema en un capítulo posterior.
+
+En este libro encontrará dos tipos de capítulos: capítulos de conceptos y capítulos de proyectos. En los capítulos de concepto, aprenderás sobre un aspecto de Rust. En los capítulos de proyectos
+En los capítulos de proyectos, construiremos juntos pequeños programas, aplicando lo que has aprendido hasta ahora.
+hasta ahora. Los capítulos 2, 12 y 20 son capítulos de proyectos; el resto son capítulos de conceptos.
+
+El capítulo 1 explica cómo instalar Rust, cómo escribir un programa "¡Hola, mundo!
+y cómo utilizar Cargo, el gestor de paquetes y la herramienta de construcción de Rust. El capítulo 2 es una
+introducción práctica al lenguaje Rust. Aquí cubrimos los conceptos a un nivel alto, y los capítulos posteriores proporcionarán detalles adicionales. Si quieres ensuciarte las manos de inmediato, el capítulo 2 es el lugar adecuado para ello. Al principio, es posible que
+Incluso puede que quieras saltarte el capítulo 3, que cubre características de Rust similares a las de otros lenguajes de programación, y pasar directamente al capítulo 3.
+de otros lenguajes de programación, y pasar directamente al capítulo 4 para aprender sobre
+sistema de propiedad de Rust. Sin embargo, si eres un aprendiz particularmente meticuloso
+que prefiere aprender cada detalle antes de pasar al siguiente, puede que quiera
+saltarse el Capítulo 2 e ir directamente al Capítulo 3, volviendo al Capítulo 2 cuando
+cuando quieras trabajar en un proyecto aplicando los detalles que has aprendido.
+
+El capítulo 5 trata de los structs y los métodos, y el capítulo 6 cubre los enums, las expresiones `match
+y la construcción de flujo de control `if let`. Utilizarás structs y
+enums para crear tipos personalizados en Rust.
+
+En el Capítulo 7, aprenderás sobre el sistema de módulos de Rust y sobre las reglas de privacidad
+para organizar tu código y su Interfaz de Programación de Aplicaciones pública
+(API). El capítulo 8 discute algunas estructuras de datos de colección comunes que la
+biblioteca estándar proporciona, como los vectores, las cadenas y los mapas hash. El capítulo 9
+explora la filosofía y las técnicas de gestión de errores de Rust.
+
+El capítulo 10 profundiza en los genéricos, los rasgos y los tiempos de vida, que te dan el poder
+para definir código que se aplica a múltiples tipos. El capítulo 11 trata de las pruebas,
+que incluso con las garantías de seguridad de Rust es necesario para asegurar que la lógica de tu programa es correcta.
+lógica de tu programa es correcta. En el Capítulo 12, construiremos nuestra propia implementación de un subconjunto
+de funcionalidad de la herramienta de línea de comandos `grep` que busca texto
+dentro de los archivos. Para esto, usaremos muchos de los conceptos que discutimos en los
+capítulos anteriores.
+
+El capítulo 13 explora los cierres e iteradores: características de Rust que provienen de
+de los lenguajes de programación funcionales. En el capítulo 14, examinaremos Cargo con más
+profundidad y hablaremos de las mejores prácticas para compartir tus bibliotecas con otros.
+El capítulo 15 trata de los punteros inteligentes que proporciona la biblioteca estándar y los
+rasgos que permiten su funcionalidad.
+
+En el capítulo 16, recorreremos diferentes modelos de programación concurrente
+y hablaremos de cómo Rust te ayuda a programar en múltiples hilos sin miedo.
+El capítulo 17 examina cómo el lenguaje de Rust se compara con los principios de la programación orientada a objetos
+con los que puede estar familiarizado.
+
+El capítulo 18 es una referencia a los patrones y a la concordancia de patrones, que son poderosas
+formas de expresar ideas en los programas de Rust.
+El capítulo 19 contiene temas avanzados de gran interes, incluyendo Rust inseguro, macros, y
+más sobre tiempos de vida, rasgos, tipos, funciones y cierres.
+
+En el capítulo 20, completaremos un proyecto en el que implementaremos un servidor web de bajo nivel
+multihilo de bajo nivel.
+
+Por último, algunos apéndices contienen información útil sobre el lenguaje a través de un formato de referencia.
+El Apéndice A cubre las palabras clave de Rust, el Apéndice B
+cubre los operadores y símbolos de Rust, el Apéndice C cubre los rasgos derivables
+de la biblioteca estándar, el Apéndice D cubre algunas herramientas de desarrollo útiles, y el Apéndice E
+de desarrollo, y el Apéndice E explica las ediciones de Rust.
+
+No hay una forma incorrecta de leer este libro: si quieres saltarlo, hazlo.
+Puede que tenga que volver a los capítulos anteriores si experimenta alguna
+confusión. Pero haz lo que te funcione.
-An important part of the process of learning Rust is learning how to read the
-error messages the compiler displays: these will guide you toward working code.
-As such, we’ll provide many examples that don’t compile along with the error
-message the compiler will show you in each situation. Know that if you enter
-and run a random example, it may not compile! Make sure you read the
-surrounding text to see whether the example you’re trying to run is meant to
-error. Ferris will also help you distinguish code that isn’t meant to work:
+Una parte importante del proceso de aprendizaje de Rust es aprender a leer los
+mensajes de error que muestra el compilador: estos te guiarán hacia un código que funcione.
+Como tal, proporcionaremos muchos ejemplos que no compilan junto con el mensaje de error que el compilador mostrará en cada situación.
+que el compilador le mostrará en cada situación. Sepa que si introduce
+y ejecuta un ejemplo al azar, ¡puede que no compile! Asegúrese de leer el
+texto circundante para ver si el ejemplo que está tratando de ejecutar está destinado a
+error. Ferris también te ayudará a distinguir el código que no está destinado a funcionar:
-| Ferris | Meaning |
+| Ferris | Meaning |
|------------------------------------------------------------------------|--------------------------------------------------|
-|
| This code does not compile! |
-|
| This code panics! |
-|
| This code block contains unsafe code. |
-|
| This code does not produce the desired behavior. |
+|
| ¡Este código no compila! |
+|
| Este código se bloquea! |
+|
| Este bloque de código contiene código inseguro. |
+|
| Este código no produce el comportamiento deseado. |
-In most situations, we’ll lead you to the correct version of any code that
-doesn’t compile.
+En la mayoría de las situaciones, le llevaremos a la versión correcta de cualquier código que
+no compila.
-## Source Code
+## Código fuente
-The source files from which this book is generated can be found on
+Los archivos fuente a partir de los cuales se ha generado este libro pueden encontrarse en
[GitHub][book].
[book]: https://github.com/rust-lang/book/tree/master/src
diff --git a/src/ch01-00-getting-started.md b/src/ch01-00-getting-started.md
index ff5e324f7a..874eda4329 100644
--- a/src/ch01-00-getting-started.md
+++ b/src/ch01-00-getting-started.md
@@ -1,8 +1,8 @@
-# Getting Started
+# Cómo empezar
-Let’s start your Rust journey! There’s a lot to learn, but every journey starts
-somewhere. In this chapter, we’ll discuss:
+Empecemos tu viaje por Rust!Hay mucho que aprender, pero todo viaje comienza en alguna parte.
+En este capítulo, discutiremos:
-* Installing Rust on Linux, macOS, and Windows
-* Writing a program that prints `Hello, world!`
-* Using `cargo`, Rust’s package manager and build system
+* Instalación de Rust en Linux, macOS y Windows
+* Escribir un programa que imprima `¡Hola, mundo!`
+* Usando `cargo`, el gestor de paquetes y sistema de construcción de Rust.
diff --git a/src/ch01-01-installation.md b/src/ch01-01-installation.md
index f343d50094..0daaa332be 100644
--- a/src/ch01-01-installation.md
+++ b/src/ch01-01-installation.md
@@ -1,118 +1,118 @@
-## Installation
+## Instalación
-The first step is to install Rust. We’ll download Rust through `rustup`, a
-command line tool for managing Rust versions and associated tools. You’ll need
-an internet connection for the download.
+El primer paso es instalar Rust. Vamos a descargar Rust a través de `rustup`, una
+herramienta de línea de comandos para gestionar las versiones de Rust y las herramientas asociadas. Necesitarás
+una conexión a Internet para la descarga.
-> Note: If you prefer not to use `rustup` for some reason, please see [the Rust
-> installation page](https://www.rust-lang.org/tools/install) for other options.
+> Nota: Si prefiere no usar `rustup` por alguna razón, por favor vea [la página de instalación de Rust
+> página de instalación](https://www.rust-lang.org/tools/install) para conocer otras opciones.
-The following steps install the latest stable version of the Rust compiler.
-Rust’s stability guarantees ensure that all the examples in the book that
-compile will continue to compile with newer Rust versions. The output might
-differ slightly between versions, because Rust often improves error messages
-and warnings. In other words, any newer, stable version of Rust you install
-using these steps should work as expected with the content of this book.
+Los siguientes pasos instalan la última versión estable del compilador de Rust.
+Las garantías de estabilidad de Rust aseguran que todos los ejemplos del libro que
+compilan seguirán compilando con las nuevas versiones de Rust. La salida puede
+diferir ligeramente entre versiones, porque Rust a menudo mejora los mensajes de error
+y advertencias. En otras palabras, cualquier versión más nueva y estable de Rust que instales
+usando estos pasos debería funcionar como se espera con el contenido de este libro.
-> ### Command Line Notation
+> ### Notación de la línea de comandos
>
-> In this chapter and throughout the book, we’ll show some commands used in the
-> terminal. Lines that you should enter in a terminal all start with `$`. You
-> don’t need to type in the `$` character; it indicates the start of each
-> command. Lines that don’t start with `$` typically show the output of the
-> previous command. Additionally, PowerShell-specific examples will use `>`
-> rather than `$`.
+> En este capítulo y a lo largo del libro, mostraremos algunos comandos utilizados en el
+> terminal. Las líneas que debes introducir en una terminal comienzan todas con `$`. Usted
+> No es necesario que escriba el carácter `$`; indica el comienzo de cada comando.
+> comando. Las líneas que no comienzan con `$` normalmente muestran la salida del
+> comando anterior. Además, los ejemplos específicos de PowerShell utilizarán `>`
+> en lugar de `$`.
-### Installing `rustup` on Linux or macOS
+### Instalación de `rustup` en Linux o macOS
-If you’re using Linux or macOS, open a terminal and enter the following command:
+Si utilizas Linux o macOS, abre un terminal e introduce el siguiente comando:
```console
$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
```
-The command downloads a script and starts the installation of the `rustup`
-tool, which installs the latest stable version of Rust. You might be prompted
-for your password. If the install is successful, the following line will appear:
+El comando descarga un script e inicia la instalación de la herramienta `rustup
+que instala la última versión estable de Rust. Es posible que se le pida
+su contraseña. Si la instalación tiene éxito, aparecerá la siguiente línea:
```text
Rust is installed now. Great!
```
-Additionally, you’ll need a linker of some kind. It’s likely one is already
-installed, but when you try to compile a Rust program and get errors indicating
-that a linker could not execute, that means a linker isn’t installed on your
-system and you’ll need to install one manually. C compilers usually come with
-the correct linker. Check your platform’s documentation for how to install a C
-compiler. Also, some common Rust packages depend on C code and will need a C
-compiler. Therefore, it might be worth installing one now.
+Además, necesitarás un enlazador de algún tipo. Es probable que uno ya esté
+instalado, pero cuando intentas compilar un programa de Rust y obtienes errores indicando
+que un enlazador no pudo ejecutarse, eso significa que un enlazador no está instalado en tu
+sistema y tendrás que instalar uno manualmente. Los compiladores de C suelen venir con
+el enlazador correcto. Consulta la documentación de tu plataforma para saber cómo instalar un compilador de C
+para instalar un compilador de C. Además, algunos paquetes comunes de Rust dependen del código C y necesitarán un compilador C
+C. Por lo tanto, podría valer la pena instalar uno ahora.
-### Installing `rustup` on Windows
+### Instalación de `rustup` en Windows
-On Windows, go to [https://www.rust-lang.org/tools/install][install] and follow
-the instructions for installing Rust. At some point in the installation, you’ll
-receive a message explaining that you’ll also need the C++ build tools for
-Visual Studio 2013 or later. The easiest way to acquire the build tools is to
-install [Build Tools for Visual Studio 2019][visualstudio]. When asked which
-workloads to install make sure "C++ build tools" is selected and that the
-Windows 10 SDK and the English language pack components are included.
+En Windows, vaya a [https://www.rust-lang.org/tools/install][install] y siga
+las instrucciones para instalar Rust. En algún momento de la instalación, recibirás un mensaje
+recibirás un mensaje explicando que también necesitarás las herramientas de compilación de C++ para
+Visual Studio 2013 o posterior. La forma más sencilla de adquirir las herramientas de compilación es
+instalar [Build Tools for Visual Studio 2019][visualstudio]. Cuando se le pregunte qué
+cargas de trabajo instalar asegúrese de que se selecciona "C++ build tools" y que el
+SDK de Windows 10 y los componentes del paquete de idioma inglés estén incluidos.
[install]: https://www.rust-lang.org/tools/install
[visualstudio]: https://visualstudio.microsoft.com/visual-cpp-build-tools/
-The rest of this book uses commands that work in both *cmd.exe* and PowerShell.
-If there are specific differences, we’ll explain which to use.
+El resto de este libro utiliza comandos que funcionan tanto en *cmd.exe* como en PowerShell.
+Si hay diferencias específicas, explicaremos cuál usar.
-### Updating and Uninstalling
+### Actualización y desinstalación
-After you’ve installed Rust via `rustup`, updating to the latest version is
-easy. From your shell, run the following update script:
+Después de haber instalado Rust a través de `rustup`, la actualización a la última versión es
+fácil. Desde tu shell, ejecuta el siguiente script de actualización:
```console
$ rustup update
```
-To uninstall Rust and `rustup`, run the following uninstall script from your
+Para desinstalar Rust y `rustup`, ejecute el siguiente script de desinstalación desde su
shell:
```console
$ rustup self uninstall
```
-### Troubleshooting
+### Solución de problemas
-To check whether you have Rust installed correctly, open a shell and enter this
-line:
+Para comprobar si tienes Rust instalado correctamente, abre un shell e introduce esta
+línea:
```console
$ rustc --version
```
-You should see the version number, commit hash, and commit date for the latest
-stable version that has been released in the following format:
+Debería ver el número de versión, el hash de confirmación y la fecha de confirmación de la última
+versión estable que se ha publicado en el siguiente formato:
```text
rustc x.y.z (abcabcabc yyyy-mm-dd)
```
-If you see this information, you have installed Rust successfully! If you don’t
-see this information and you’re on Windows, check that Rust is in your `%PATH%`
-system variable. If that’s all correct and Rust still isn’t working, there are
-a number of places you can get help. The easiest is the #beginners channel on
-[the official Rust Discord][discord]. There, you can chat with other Rustaceans
-(a silly nickname we call ourselves) who can help you out. Other great
-resources include [the Users forum][users] and [Stack Overflow][stackoverflow].
+Si ves esta información, ¡has instalado Rust con éxito! Si no ve
+esta información y estás en Windows, comprueba que Rust está en tu variable de sistema `%PATH%`.
+en tu variable de sistema. Si todo esto es correcto y Rust sigue sin funcionar, hay
+varios lugares donde puedes obtener ayuda. El más fácil es el canal #beginners en
+[el Discord oficial de Rust][discord]. Allí, puedes chatear con otros Rustaceans
+(un tonto apodo con el que nos llamamos a nosotros mismos) que pueden ayudarte. Otros grandes
+recursos incluyen [el foro de usuarios][usuarios] y [Stack Overflow][stackoverflow].
[discord]: https://discord.gg/rust-lang
[users]: https://users.rust-lang.org/
[stackoverflow]: https://stackoverflow.com/questions/tagged/rust
-### Local Documentation
+### Documentación local
-The installation of Rust also includes a copy of the documentation locally, so
-you can read it offline. Run `rustup doc` to open the local documentation in
-your browser.
+La instalación de Rust también incluye una copia de la documentación localmente, para que
+puedes leerla fuera de línea. Ejecute `rustup doc` para abrir la documentación local en
+tu navegador.
-Any time a type or function is provided by the standard library and you’re not
-sure what it does or how to use it, use the application programming interface
-(API) documentation to find out!
+Cada vez que un tipo o función es proporcionada por la biblioteca estándar y no estás
+no está seguro de lo que hace o de cómo utilizarlo, utilice la documentación de la interfaz de
+(API) para averiguarlo.
diff --git a/src/ch01-02-hello-world.md b/src/ch01-02-hello-world.md
index 69f59dfc98..99ccbabb6b 100644
--- a/src/ch01-02-hello-world.md
+++ b/src/ch01-02-hello-world.md
@@ -1,66 +1,66 @@
-## Hello, World!
+## ¡Hola, mundo
-Now that you’ve installed Rust, let’s write your first Rust program. It’s
-traditional when learning a new language to write a little program that prints
-the text `Hello, world!` to the screen, so we’ll do the same here!
+Ahora que has instalado Rust, vamos a escribir tu primer programa en Rust.
+Es tradición cuando se aprende un nuevo lenguaje escribir un pequeño programa que
+imprima el texto `¡Hola, mundo!` en la pantalla, así que haremos lo mismo aquí.
-> Note: This book assumes basic familiarity with the command line. Rust makes
-> no specific demands about your editing or tooling or where your code lives, so
-> if you prefer to use an integrated development environment (IDE) instead of
-> the command line, feel free to use your favorite IDE. Many IDEs now have some
-> degree of Rust support; check the IDE’s documentation for details. Recently,
-> the Rust team has been focusing on enabling great IDE support, and progress
-> has been made rapidly on that front!
+> Nota: Este libro asume una familiaridad básica con la línea de comandos. Rust no hace
+> demandas específicas sobre su edición o herramientas o donde vive su código, así
+> que si usted prefiere usar un entorno de desarrollo integrado (IDE) en lugar de
+> la línea de comandos, siéntase libre de usar su IDE favorito. Muchos IDEs tienen
+> ahora algún grado de soporte para Rust; comprueba la documentación del IDE para más detalles.
+> Recientemente, el equipo de Rust se ha centrado en habilitar un gran soporte de IDE,
+> ¡y se ha progresado rápidamente en ese frente!
-### Creating a Project Directory
+### Creando un directorio de proyecto
-You’ll start by making a directory to store your Rust code. It doesn’t matter
-to Rust where your code lives, but for the exercises and projects in this book,
-we suggest making a *projects* directory in your home directory and keeping all
-your projects there.
+Empezarás por crear un directorio para almacenar tu código Rust. A Rust no le importa
+dónde vive su código, pero para los ejercicios y proyectos de este libro,
+sugerimos hacer un directorio de *proyectos* en su directorio personal y mantener
+todos sus proyectos allí.
-Open a terminal and enter the following commands to make a *projects* directory
-and a directory for the “Hello, world!” project within the *projects* directory.
+Abre un terminal e introduce los siguientes comandos para crear un directorio de *proyectos*
+y un directorio para el proyecto "¡Hola, mundo!" dentro del directorio de *proyectos*.
-For Linux, macOS, and PowerShell on Windows, enter this:
+Para Linux, macOS y PowerShell en Windows, introduzca esto:
```console
-$ mkdir ~/projects
-$ cd ~/projects
-$ mkdir hello_world
-$ cd hello_world
+mkdir ~/proyecto
+cd ~/proyecto
+mkdir hola_mundo
+cd hola_mundo
```
-For Windows CMD, enter this:
+Para el CMD de Windows, introduzca lo siguiente
```cmd
-> mkdir "%USERPROFILE%\projects"
-> cd /d "%USERPROFILE%\projects"
-> mkdir hello_world
-> cd hello_world
+> mkdir "%USERPROFILE%\projectos"
+> cd /d "%USERPROFILE%\projectos"
+> mkdir hola_mundo
+> cd hola_mundo
```
-### Writing and Running a Rust Program
+### Escribir y ejecutar un programa de Rust
-Next, make a new source file and call it *main.rs*. Rust files always end with
-the *.rs* extension. If you’re using more than one word in your filename, use
-an underscore to separate them. For example, use *hello_world.rs* rather than
-*helloworld.rs*.
+A continuación, crea un nuevo archivo fuente y llámalo *main.rs*. Los archivos
+Rust siempre terminan con la extensión *.rs.* Si utilizas más de una palabra en tu nombre de archivo, utiliza
+un guión bajo para separarlas. Por ejemplo, usa hola_mundo.rs en lugar de holamundo.rs.
-Now open the *main.rs* file you just created and enter the code in Listing 1-1.
+Ahora abre el archivo *main.rs* que acabas de crear e introduce el código del Listado 1-1.
-Filename: main.rs
+ Nombre del archivo: main.rs
```rust
fn main() {
- println!("Hello, world!");
+ println!("¡Hola, mundo!");
}
```
-Listing 1-1: A program that prints `Hello, world!`
+Listado 1-1 Un programa que imprime `¡Hola, mundo!`
-Save the file and go back to your terminal window. On Linux or macOS, enter
-the following commands to compile and run the file:
+Guarda el archivo y vuelve a la ventana de tu terminal.
+En Linux o macOS, introduce los siguientes
+comandos para compilar y ejecutar el archivo:
```console
$ rustc main.rs
@@ -68,26 +68,26 @@ $ ./main
Hello, world!
```
-On Windows, enter the command `.\main.exe` instead of `./main`:
+En Windows, introduzca el comando `.\main.exe`en lugar de `./main`:
```powershell
> rustc main.rs
> .\main.exe
-Hello, world!
+¡Hola, mundo!
```
-Regardless of your operating system, the string `Hello, world!` should print to
-the terminal. If you don’t see this output, refer back to the
-[“Troubleshooting”][troubleshooting] part of the Installation
-section for ways to get help.
+Independientemente de su sistema operativo, la cadena `¡Hola, mundo!` debería imprimirse
+en el terminal. Si no ve esta salida, consulte la parte de
+[“Solución de problemas”][troubleshooting] de la sección de Instalación
+para obtener ayuda.
-If `Hello, world!` did print, congratulations! You’ve officially written a Rust
-program. That makes you a Rust programmer—welcome!
+Si, `¡Hola, mundo!` se imprime, ¡felicidades! Has escrito oficialmente un programa en Rust.
+Eso te convierte en un programador de Rust, ¡bienvenido!
-### Anatomy of a Rust Program
+### Anatomía de un programa Rust
-Let’s review in detail what just happened in your “Hello, world!” program.
-Here’s the first piece of the puzzle:
+Revisemos en detalle lo que acaba de suceder en tu programa "¡Hola, mundo!"
+Aquí está la primera pieza del rompecabezas:
```rust
fn main() {
@@ -95,65 +95,63 @@ fn main() {
}
```
-These lines define a function in Rust. The `main` function is special: it is
-always the first code that runs in every executable Rust program. The first
-line declares a function named `main` that has no parameters and returns
-nothing. If there were parameters, they would go inside the parentheses, `()`.
+Estas líneas definen una función en Rust. La función `main` es especial:
+siempre es el primer código que se ejecuta en todo programa ejecutable de Rust. La primera
+línea declara una función llamada `main` que no tiene parámetros y no devuelve nada.
+Si hubiera parámetros, irían dentro de los paréntesis, `()`.
-Also, note that the function body is wrapped in curly brackets, `{}`. Rust
-requires these around all function bodies. It’s good style to place the opening
-curly bracket on the same line as the function declaration, adding one space in
-between.
+Además, observe que el cuerpo de la función está encerrado entre llaves, `{}`. Rust
+requiere estos alrededor de todos los cuerpos de las funciones. Es un buen estilo
+colocar la llave de apertura en la misma línea que la declaración
+de la función, añadiendo un espacio en medio.
-If you want to stick to a standard style across Rust projects, you can use an
-automatic formatter tool called `rustfmt` to format your code in a particular
-style. The Rust team has included this tool with the standard Rust distribution,
-like `rustc`, so it should already be installed on your computer! Check the
-online documentation for more details.
+Si quieres mantener un estilo estándar en todos los proyectos de Rust, puedes usar
+una herramienta de formato automático llamada `rustfmt` para formatear
+tu código en un estilo particular. El equipo de Rust ha incluido esta herramienta
+con la distribución estándar de Rust, al igual que `rustc`, por lo que ya debería estar
+instalada en tu ordenador. Consulta la documentación online para más detalles.
-Inside the `main` function is the following code:
+Dentro de la función `main` está el siguiente código:
```rust
- println!("Hello, world!");
+ println!("¡Hola, mundo!");
```
-This line does all the work in this little program: it prints text to the
-screen. There are four important details to notice here.
+Esta línea hace todo el trabajo en este pequeño programa:
+imprime el texto en la pantalla. Hay cuatro detalles importantes a tener en cuenta aquí.
-First, Rust style is to indent with four spaces, not a tab.
+Primero, el estilo Rust es indentar con cuatro espacios, y no con un tabulador.
-Second, `println!` calls a Rust macro. If it called a function instead, it
-would be entered as `println` (without the `!`). We’ll discuss Rust macros in
-more detail in Chapter 19. For now, you just need to know that using a `!`
-means that you’re calling a macro instead of a normal function.
+Segundo, `println!` llama a una macro de Rust. Si en cambio llamara a una función, se
+introduciría como `println` (sin el `!`). Hablaremos de las macros de Rust con
+más detalle en el capítulo 19. Por ahora, sólo necesitas saber que usar una `!` significa
+que estás llamando a una macro en lugar de a una función normal.
-Third, you see the `"Hello, world!"` string. We pass this string as an argument
-to `println!`, and the string is printed to the screen.
+En tercer lugar, ves la cadena `"¡Hola, mundo!"`. Pasamos esta cadena como argumento
+a `println!`, y la cadena se imprime en la pantalla.
-Fourth, we end the line with a semicolon (`;`), which indicates that this
-expression is over and the next one is ready to begin. Most lines of Rust code
-end with a semicolon.
+En cuarto lugar, terminamos la línea con un punto y coma (`;`), que indica
+que esta expresión ha terminado y la siguiente está lista para comenzar. La mayoría de
+las líneas de código de Rust terminan con un punto y coma.
-### Compiling and Running Are Separate Steps
+### Compilar y ejecutar son pasos separados
-You’ve just run a newly created program, so let’s examine each step in the
-process.
+Acabas de ejecutar un programa recién creado, así que vamos a
+examinar cada paso del proceso.
-Before running a Rust program, you must compile it using the Rust compiler by
-entering the `rustc` command and passing it the name of your source file, like
-this:
+Antes de ejecutar un programa Rust, debes compilarlo usando el compilador Rust
+introduciendo el comando `rustc` y pasándole el nombre de tu archivo fuente, de esta manera:
```console
-$ rustc main.rs
+rustc main.rs
```
-If you have a C or C++ background, you’ll notice that this is similar to `gcc`
-or `clang`. After compiling successfully, Rust outputs a binary executable.
+Si tienes experiencia en C o C++, notarás que esto es similar a `gcc` o `clang`.
+Después de compilar con éxito, Rust produce un ejecutable binario.
-On Linux, macOS, and PowerShell on Windows, you can see the executable by
-entering the `ls` command in your shell. On Linux and macOS, you’ll see two
-files. With PowerShell on Windows, you’ll see the same three files that you
-would see using CMD.
+En Linux, macOS y PowerShell en Windows, puedes ver el ejecutable introduciendo el
+comando `ls` en tu shell. En Linux y macOS, verás dos archivos.
+Con PowerShell en Windows, verás los mismos tres archivos que verías usando CMD.
```console
$ ls
@@ -163,36 +161,36 @@ main main.rs
With CMD on Windows, you would enter the following:
```cmd
-> dir /B %= the /B option says to only show the file names =%
+> dir /B %= the /B indica que sólo se muestren los nombres de los archivos =%
main.exe
main.pdb
main.rs
```
-This shows the source code file with the *.rs* extension, the executable file
-(*main.exe* on Windows, but *main* on all other platforms), and, when using
-Windows, a file containing debugging information with the *.pdb* extension.
-From here, you run the *main* or *main.exe* file, like this:
+Esto muestra el archivo de código fuente con la
+extensión *.rs,* el archivo ejecutable (main.exe en Windows, pero main en todas
+las demás plataformas), y, cuando se utiliza Windows, un archivo que contiene información
+de depuración con la extensión *.pdb.* Desde aquí, se ejecuta el
+archivo *main* o *main.exe*, como se indica a continuación:
```console
-$ ./main # or .\main.exe on Windows
+./main # or .\main.exe en Windows
```
-If *main.rs* was your “Hello, world!” program, this line would print `Hello,
-world!` to your terminal.
-
-If you’re more familiar with a dynamic language, such as Ruby, Python, or
-JavaScript, you might not be used to compiling and running a program as
-separate steps. Rust is an *ahead-of-time compiled* language, meaning you can
-compile a program and give the executable to someone else, and they can run it
-even without having Rust installed. If you give someone a *.rb*, *.py*, or
-*.js* file, they need to have a Ruby, Python, or JavaScript implementation
-installed (respectively). But in those languages, you only need one command to
-compile and run your program. Everything is a trade-off in language design.
-
-Just compiling with `rustc` is fine for simple programs, but as your project
-grows, you’ll want to manage all the options and make it easy to share your
-code. Next, we’ll introduce you to the Cargo tool, which will help you write
-real-world Rust programs.
+Si *main.rs* es tu programa "¡Hola, mundo!", esta línea imprimiría `¡Hola,
+mundo!` en tu terminal.
+
+Si estás más familiarizado con un lenguaje dinámico, como Ruby, Python o
+JavaScript, puede que no estés acostumbrado a compilar y ejecutar un programa
+como pasos separados. Rust es un *lenguaje compilado por adelantado*, lo que significa que puedes
+compilar un programa y darle el ejecutable a otra persona, y ésta podrá ejecutarlo incluso sin
+tener Rust instalado. Si le das a alguien un archivo *.rb*, *.py* o *.js,* necesita tener instalada una
+implementación de Ruby, Python o JavaScript (respectivamente). Pero en esos lenguajes, sólo necesitas un comando
+para compilar y ejecutar tu programa. Todo es una compensación en el diseño del lenguaje.
+
+Sólo compilar con `rustc` está bien para programas simples, pero a medida
+que tu proyecto crece, querrás manejar todas las opciones y facilitar el compartir
+tu código. A continuación, te presentaremos la herramienta Cargo, que te
+ayudará a escribir programas Rust del mundo real.
[troubleshooting]: ch01-01-installation.html#troubleshooting
diff --git a/src/ch01-03-hello-cargo.md b/src/ch01-03-hello-cargo.md
index 0f11be8ade..6e8173b699 100644
--- a/src/ch01-03-hello-cargo.md
+++ b/src/ch01-03-hello-cargo.md
@@ -1,63 +1,63 @@
-## Hello, Cargo!
-
-Cargo is Rust’s build system and package manager. Most Rustaceans use this tool
-to manage their Rust projects because Cargo handles a lot of tasks for you,
-such as building your code, downloading the libraries your code depends on, and
-building those libraries. (We call libraries your code needs *dependencies*.)
-
-The simplest Rust programs, like the one we’ve written so far, don’t have any
-dependencies. So if we had built the “Hello, world!” project with Cargo, it
-would only use the part of Cargo that handles building your code. As you write
-more complex Rust programs, you’ll add dependencies, and if you start a project
-using Cargo, adding dependencies will be much easier to do.
-
-Because the vast majority of Rust projects use Cargo, the rest of this book
-assumes that you’re using Cargo too. Cargo comes installed with Rust if you
-used the official installers discussed in the
-[“Installation”][installation] section. If you installed Rust
-through some other means, check whether Cargo is installed by entering the
-following into your terminal:
+## ¡Hola, Cargo!
+
+Cargo es el sistema de construcción y el gestor de paquetes de Rust. La mayoría de los Rustaceanos usan esta herramienta
+para gestionar sus proyectos de Rust porque Cargo maneja muchas tareas por ti,
+como construir tu código, descargar las bibliotecas de las que depende tu código y
+construir esas bibliotecas. (Llamamos a las bibliotecas que tu código necesita *dependencias*).
+
+Los programas más simples de Rust, como el que hemos escrito hasta ahora, no tienen ninguna
+dependencias. Así que si hubiéramos construido el proyecto "¡Hola, mundo!" con Cargo, éste
+sólo utilizaría la parte de Cargo que se encarga de construir su código. A medida que escribas
+programas Rust más complejos, añadirás dependencias, y si empiezas un proyecto
+usando Cargo, añadir dependencias será mucho más fácil de hacer.
+
+ebido a que la gran mayoría de los proyectos de Rust utilizan Cargo, el resto de este libro
+asume que tú también usas Cargo. Cargo viene instalado con Rust si
+usaste los instaladores oficiales discutidos en la sección
+["Instalación"][instalación] sección. Si instalaste Rust
+por algún otro medio, comprueba si Cargo está instalado introduciendo lo
+siguiente en su terminal:
```console
$ cargo --version
```
-If you see a version number, you have it! If you see an error, such as `command
-not found`, look at the documentation for your method of installation to
-determine how to install Cargo separately.
+Si ves un número de versión, lo tienes. Si ve un error, como `command
+not found`, consulte la documentación de su método de instalación para
+determinar cómo instalar Cargo por separado.
-### Creating a Project with Cargo
+### Creación de un proyecto con Cargo
-Let’s create a new project using Cargo and look at how it differs from our
-original “Hello, world!” project. Navigate back to your *projects* directory (or
-wherever you decided to store your code). Then, on any operating system, run
-the following:
+Vamos a crear un nuevo proyecto con Cargo y a ver en qué se diferencia de nuestro proyecto
+proyecto original "¡Hola, mundo!". Vuelve a tu directorio de *proyectos* (o
+donde hayas decidido almacenar tu código). A continuación, en cualquier sistema operativo, ejecute
+lo siguiente:
```console
$ cargo new hello_cargo
$ cd hello_cargo
```
-The first command creates a new directory called *hello_cargo*. We’ve named
-our project *hello_cargo*, and Cargo creates its files in a directory of the
-same name.
+El primer comando crea un nuevo directorio llamado *hello_cargo*. Hemos llamado a nuestro proyecto
+nuestro proyecto *hello_cargo*, y Cargo crea sus archivos en un directorio del
+mismo nombre.
-Go into the *hello_cargo* directory and list the files. You’ll see that Cargo
-has generated two files and one directory for us: a *Cargo.toml* file and a
-*src* directory with a *main.rs* file inside.
+Entre en el directorio *hello_cargo* y liste los archivos. Verás que Cargo
+ha generado dos archivos y un directorio para nosotros: un archivo *Cargo.toml* y un directorio
+directorio *src* con un archivo *main.rs* dentro.
-It has also initialized a new Git repository along with a *.gitignore* file.
-Git files won’t be generated if you run `cargo new` within an existing Git
-repository; you can override this behavior by using `cargo new --vcs=git`.
+También ha inicializado un nuevo repositorio Git junto con un archivo *.gitignore*.
+Los archivos Git no se generarán si ejecutas `cargo new` dentro de un repositorio Git
+existente; puedes anular este comportamiento usando `cargo new --vcs=git`.
-> Note: Git is a common version control system. You can change `cargo new` to
-> use a different version control system or no version control system by using
-> the `--vcs` flag. Run `cargo new --help` to see the available options.
+> Nota: Git es un sistema de control de versiones común. Puede cambiar `cargo new` para
+> usar un sistema de control de versiones diferente o ningún sistema de control de versiones usando
+> la bandera `--vcs`. Ejecute `cargo new --help` para ver las opciones disponibles.
-Open *Cargo.toml* in your text editor of choice. It should look similar to the
-code in Listing 1-2.
+Abra *Cargo.toml* en su editor de texto preferido. Debería ser similar al código
+código del Listado 1-2.
-Filename: Cargo.toml
+Nombre del archivo: Cargo.toml
```toml
[package]
@@ -69,30 +69,30 @@ edition = "2018"
[dependencies]
```
-Listing 1-2: Contents of *Cargo.toml* generated by `cargo
+Listado 1-2: Contenido de *Cargo.toml* generado por `cargo
new`
-This file is in the [*TOML*](https://toml.io) (*Tom’s Obvious,
-Minimal Language*) format, which is Cargo’s configuration format.
+Este archivo está en el [*TOML*](https://toml.io) (*Tom's Obvious,
+Minimal Language*), que es el formato de configuración de Cargo.
-The first line, `[package]`, is a section heading that indicates that the
-following statements are configuring a package. As we add more information to
-this file, we’ll add other sections.
+La primera línea, `[package]`, es un título de sección que indica que las
+siguientes declaraciones están configurando un package. A medida que agreguemos más información a
+este archivo, añadiremos otras secciones.
-The next four lines set the configuration information Cargo needs to compile
-your program: the name, the version, who wrote it, and the edition of Rust to
-use. Cargo gets your name and email information from your environment, so if
-that information is not correct, fix the information now and then save the
-file. We’ll talk about the `edition` key in Appendix E.
+Las siguientes cuatro líneas establecen la información de configuración que Cargo necesita para compilar
+su programa: el nombre, la versión, quién lo escribió, y la edición de Rust a
+utilizar. Cargo obtiene la información de tu nombre y correo electrónico de tu entorno, así que si
+esa información no es correcta, corrige la información ahora y luego guarda el
+archivo. Hablaremos de la clave `edition` en el Apéndice E.
-The last line, `[dependencies]`, is the start of a section for you to list any
-of your project’s dependencies. In Rust, packages of code are referred to as
-*crates*. We won’t need any other crates for this project, but we will in the
-first project in Chapter 2, so we’ll use this dependencies section then.
+La última línea, `[dependencias]`, es el comienzo de una sección para que usted liste cualquier
+de las dependencias de tu proyecto. En Rust, los package de código se denominan
+*crates*. No necesitaremos ninguna otra crate para este proyecto, pero lo haremos en el
+primer proyecto en el capítulo 2, así que usaremos esta sección de dependencias entonces.
-Now open *src/main.rs* and take a look:
+Ahora abre *src/main.rs* y echa un vistazo:
-Filename: src/main.rs
+Filename: src/main.rs
```rust
fn main() {
@@ -100,27 +100,26 @@ fn main() {
}
```
-Cargo has generated a “Hello, world!” program for you, just like the one we
-wrote in Listing 1-1! So far, the differences between our previous project and
-the project Cargo generates are that Cargo placed the code in the *src*
-directory, and we have a *Cargo.toml* configuration file in the top directory.
+Cargo ha generado un programa "¡Hola, mundo!" para ti, como el que
+¡que escribimos en el Listado 1-1! Hasta ahora, las diferencias entre nuestro proyecto anterior y
+proyecto que genera Cargo son que Cargo ha colocado el código en el directorio *src
+y que tenemos un archivo de configuración *Cargo.toml* en el directorio superior.
-Cargo expects your source files to live inside the *src* directory. The
-top-level project directory is just for README files, license information,
-configuration files, and anything else not related to your code. Using Cargo
-helps you organize your projects. There’s a place for everything, and
-everything is in its place.
+Cargo espera que sus archivos de origen estén dentro del directorio *src*. El directorio de proyecto de nivel superior
+directorio del proyecto de nivel superior es sólo para los archivos README, información de la licencia,
+archivos de configuración, y cualquier otra cosa no relacionada con su código. El uso de Cargo
+te ayuda a organizar tus proyectos. Hay un lugar para todo, y
+todo está en su lugar.
-If you started a project that doesn’t use Cargo, as we did with the “Hello,
-world!” project, you can convert it to a project that does use Cargo. Move the
-project code into the *src* directory and create an appropriate *Cargo.toml*
-file.
+Si has empezado un proyecto que no utiliza Cargo, como hicimos con el proyecto "Hello,
+world!", puedes convertirlo en un proyecto que sí utilice Cargo. Mueva el código del
+código del proyecto al directorio *src* y cree un archivo *Cargo.toml* apropiado.
-### Building and Running a Cargo Project
+### Construir y ejecutar un proyecto Cargo
-Now let’s look at what’s different when we build and run the “Hello, world!”
-program with Cargo! From your *hello_cargo* directory, build your project by
-entering the following command:
+Ahora veamos qué es diferente cuando construimos y ejecutamos el programa "¡Hola, mundo!
+¡con Cargo! Desde tu directorio *hello_cargo*, construye tu proyecto
+introduciendo el siguiente comando:
```console
$ cargo build
@@ -128,25 +127,25 @@ $ cargo build
Finished dev [unoptimized + debuginfo] target(s) in 2.85 secs
```
-This command creates an executable file in *target/debug/hello_cargo* (or
-*target\debug\hello_cargo.exe* on Windows) rather than in your current
-directory. You can run the executable with this command:
+Este comando crea un archivo ejecutable en *target/debug/hello_cargo* (o
+*target\debug\hello_cargo.exe* en Windows) en lugar de en su directorio actual
+directorio actual. Puede ejecutar el ejecutable con este comando:
```console
$ ./target/debug/hello_cargo # or .\target\debug\hello_cargo.exe on Windows
Hello, world!
```
-If all goes well, `Hello, world!` should print to the terminal. Running `cargo
-build` for the first time also causes Cargo to create a new file at the top
-level: *Cargo.lock*. This file keeps track of the exact versions of
-dependencies in your project. This project doesn’t have dependencies, so the
-file is a bit sparse. You won’t ever need to change this file manually; Cargo
-manages its contents for you.
+Si todo va bien, "Hello, world!" debería imprimirse en el terminal. Al ejecutar `cargo
+build` por primera vez también hace que Cargo cree un nuevo archivo en el nivel superior
+nivel superior: *Cargo.lock*. Este archivo mantiene un registro de las versiones exactas de
+dependencias en tu proyecto. Este proyecto no tiene dependencias, por lo que el archivo
+es un poco escaso. Nunca necesitarás cambiar este archivo manualmente; Cargo
+gestiona su contenido por ti.
-We just built a project with `cargo build` and ran it with
-`./target/debug/hello_cargo`, but we can also use `cargo run` to compile the
-code and then run the resulting executable all in one command:
+Acabamos de construir un proyecto con `cargo build` y lo ejecutamos con
+`./target/debug/hello_cargo`, pero también podemos usar `cargo run` para compilar el código
+código y luego ejecutar el ejecutable resultante todo en un solo comando:
```console
$ cargo run
@@ -155,10 +154,10 @@ $ cargo run
Hello, world!
```
-Notice that this time we didn’t see output indicating that Cargo was compiling
-`hello_cargo`. Cargo figured out that the files hadn’t changed, so it just ran
-the binary. If you had modified your source code, Cargo would have rebuilt the
-project before running it, and you would have seen this output:
+Fíjate que esta vez no vimos la salida que indica que Cargo estaba compilando
+`hello_cargo`. Cargo se dio cuenta de que los archivos no habían cambiado, así que simplemente ejecutó
+el binario. Si hubieras modificado tu código fuente, Cargo habría reconstruido el
+proyecto antes de ejecutarlo, y habrías visto esta salida:
```console
$ cargo run
@@ -168,8 +167,8 @@ $ cargo run
Hello, world!
```
-Cargo also provides a command called `cargo check`. This command quickly checks
-your code to make sure it compiles but doesn’t produce an executable:
+Cargo también proporciona un comando llamado `cargo check`. Este comando comprueba rápidamente
+su código para asegurarse de que compila pero no produce un ejecutable:
```console
$ cargo check
@@ -177,50 +176,50 @@ $ cargo check
Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs
```
-Why would you not want an executable? Often, `cargo check` is much faster than
-`cargo build`, because it skips the step of producing an executable. If you’re
-continually checking your work while writing the code, using `cargo check` will
-speed up the process! As such, many Rustaceans run `cargo check` periodically
-as they write their program to make sure it compiles. Then they run `cargo
-build` when they’re ready to use the executable.
+¿Por qué no quieres un ejecutable? Por lo general, `cargo check` es mucho más rápido que
+`cargo build`, porque se salta el paso de producir un ejecutable. Si estás
+continuamente tu trabajo mientras escribes el código, usar `cargo check` acelerará el proceso.
+acelerará el proceso. Por ello, muchos Rustaceanos ejecutan `cargo check` periódicamente
+mientras escriben su programa para asegurarse de que compila. Luego ejecutan `cargo
+build` cuando están listos para usar el ejecutable.
-Let’s recap what we’ve learned so far about Cargo:
+Recapitulemos lo que hemos aprendido hasta ahora sobre Cargo:
-* We can build a project using `cargo build`.
-* We can build and run a project in one step using `cargo run`.
-* We can build a project without producing a binary to check for errors using
+* Podemos construir un proyecto usando `cargo build`.
+* Podemos construir y ejecutar un proyecto en un solo paso usando `cargo run`.
+* Podemos construir un proyecto sin producir un binario para comprobar los errores utilizando
`cargo check`.
-* Instead of saving the result of the build in the same directory as our code,
- Cargo stores it in the *target/debug* directory.
-
-An additional advantage of using Cargo is that the commands are the same no
-matter which operating system you’re working on. So, at this point, we’ll no
-longer provide specific instructions for Linux and macOS versus Windows.
-
-### Building for Release
-
-When your project is finally ready for release, you can use `cargo build
---release` to compile it with optimizations. This command will create an
-executable in *target/release* instead of *target/debug*. The optimizations
-make your Rust code run faster, but turning them on lengthens the time it takes
-for your program to compile. This is why there are two different profiles: one
-for development, when you want to rebuild quickly and often, and another for
-building the final program you’ll give to a user that won’t be rebuilt
-repeatedly and that will run as fast as possible. If you’re benchmarking your
-code’s running time, be sure to run `cargo build --release` and benchmark with
-the executable in *target/release*.
-
-### Cargo as Convention
-
-With simple projects, Cargo doesn’t provide a lot of value over just using
-`rustc`, but it will prove its worth as your programs become more intricate.
-With complex projects composed of multiple crates, it’s much easier to let
-Cargo coordinate the build.
-
-Even though the `hello_cargo` project is simple, it now uses much of the real
-tooling you’ll use in the rest of your Rust career. In fact, to work on any
-existing projects, you can use the following commands to check out the code
-using Git, change to that project’s directory, and build:
+* En lugar de guardar el resultado de la construcción en el mismo directorio que nuestro código,
+ Cargo lo guarda en el directorio *target/debug*.
+
+Una ventaja adicional de usar Cargo es que los comandos son los mismos sin importar
+no importa el sistema operativo en el que estés trabajando. Por lo tanto, en este punto, no vamos a
+instrucciones específicas para Linux y macOS frente a Windows.
+
+### Versión de lanzamiento
+
+Cuando tu proyecto esté finalmente listo para ser lanzado, puedes usar `cargo build
+--release` para compilarlo con optimizaciones. Este comando creará un
+ejecutable en *target/release* en lugar de *target/debug*. Las optimizaciones
+hacen que tu código Rust se ejecute más rápido, pero activándolas se alarga el tiempo que tarda
+para que tu programa compile. Por eso hay dos perfiles diferentes: uno
+para el desarrollo, cuando quieres reconstruir rápidamente y a menudo, y otro para
+construir el programa final que le darás a un usuario que no será reconstruido
+repetidamente y que se ejecute lo más rápido posible. Si está evaluando el tiempo de ejecución de su código
+Si estás evaluando el tiempo de ejecución de tu código, asegúrate de ejecutar `cargo build --release` y de evaluar con
+el ejecutable en *target/release*.
+
+### Cargo como convenio
+
+Con proyectos sencillos, Cargo no aporta mucho valor sobre el uso de
+`rustc`, pero demostrará su valor a medida que sus programas se vuelvan más intrincados.
+Con proyectos complejos compuestos por múltiples crates, es mucho más fácil dejar que
+Cargo coordine la construcción.
+
+Aunque el proyecto `hello_cargo` es simple, ahora utiliza gran parte de las funciones reales
+que usarás en el resto de tu carrera en Rust. De hecho, para trabajar en cualquier
+proyectos existentes, puedes usar los siguientes comandos para comprobar el código
+usando Git, cambiar al directorio de ese proyecto, y compilar:
```console
$ git clone example.org/someproject
@@ -232,20 +231,20 @@ For more information about Cargo, check out [its documentation].
[its documentation]: https://doc.rust-lang.org/cargo/
-## Summary
+## Resumen
-You’re already off to a great start on your Rust journey! In this chapter,
-you’ve learned how to:
+Ya has empezado con buen pie tu aventura con Rust. En este capítulo,
+has aprendido cómo:
-* Install the latest stable version of Rust using `rustup`
-* Update to a newer Rust version
-* Open locally installed documentation
-* Write and run a “Hello, world!” program using `rustc` directly
-* Create and run a new project using the conventions of Cargo
+* Instalar la última versión estable de Rust usando `rustup`.
+* Actualizar a una nueva versión de Rust
+* Abrir la documentación instalada localmente
+* Escribir y ejecutar un programa "¡Hola, mundo!" utilizando directamente `rustc`.
+* Crear y ejecutar un nuevo proyecto utilizando las convenciones de Cargo
-This is a great time to build a more substantial program to get used to reading
-and writing Rust code. So, in Chapter 2, we’ll build a guessing game program.
-If you would rather start by learning how common programming concepts work in
-Rust, see Chapter 3 and then return to Chapter 2.
+Este es un buen momento para crear un programa más significativo para acostumbrarse a leer
+y escribir código Rust. A continuación , en el Capítulo 2, construiremos un programa de juego de adivinanzas.
+Si prefieres empezar aprendiendo cómo funcionan los conceptos comunes de programación en
+Rust, vea el capítulo 3 y luego vuelva al capítulo 2.
[installation]: ch01-01-installation.html#installation
diff --git a/src/ch02-00-guessing-game-tutorial.md b/src/ch02-00-guessing-game-tutorial.md
index ba494eb944..c10eef2364 100644
--- a/src/ch02-00-guessing-game-tutorial.md
+++ b/src/ch02-00-guessing-game-tutorial.md
@@ -1,275 +1,276 @@
-# Programming a Guessing Game
+# Programando un juego de predicciones
-Let’s jump into Rust by working through a hands-on project together! This
-chapter introduces you to a few common Rust concepts by showing you how to use
-them in a real program. You’ll learn about `let`, `match`, methods, associated
-functions, using external crates, and more! The following chapters will explore
-these ideas in more detail. In this chapter, you’ll practice the fundamentals.
+¡Vamos a sumergirnos en Rust trabajando en un proyecto práctico juntos! Este
+capítulo te introducirá algunos conceptos de Rust enseñándote cómo usarlos en
+un programa real. Aprenderás sobre `let`, `match`, métodos, funciones asociadas,
+utilizar cajas externas y ¡mucho más! Los siguientes capítulos explicarán estas
+ideas en más detalle. En este capítulo, practicarás las bases.
-We’ll implement a classic beginner programming problem: a guessing game. Here’s
-how it works: the program will generate a random integer between 1 and 100. It
-will then prompt the player to enter a guess. After a guess is entered, the
-program will indicate whether the guess is too low or too high. If the guess is
-correct, the game will print a congratulatory message and exit.
+Implementaremos un problema de programación para principiantes clásico. Funciona
+así: el programa generará un entero aleatorio entre 1 y 100. Luego preguntará al
+usuario para introducir una predicción. Tras introducirla, el programa indicará
+si la predicción fue muy alta o muy baja. Si la predicción fue correcta, el
+juego imprimirá un mensaje de felicitación y terminará.
-## Setting Up a New Project
+## Configurando un nuevo proyecto
-To set up a new project, go to the *projects* directory that you created in
-Chapter 1 and make a new project using Cargo, like so:
+Para configurar un nuevo proyecto, ve a la carpeta de *proyectos* que creaste
+en el capítulo 1 y haz un nuevo proyecto utilizando Cargo, por ejemplo:
```console
-$ cargo new guessing_game
-$ cd guessing_game
+$ cargo new juego_predicciones
+$ cd juego_predicciones
```
-The first command, `cargo new`, takes the name of the project (`guessing_game`)
-as the first argument. The second command changes to the new project’s
-directory.
+El primer comando, `cargo new`, utiliza el nombre del proyecto (`juego_predicciones`)
+cómo el primer argumento. El segundo comando cambia la ubicación de la
+consola al directorio del proyecto
-Look at the generated *Cargo.toml* file:
+Veamos el archivo *Cargo.toml* que se ha generado:
-Filename: Cargo.toml
+Nombre del archivo: Cargo.toml
```toml
{{#include ../listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/Cargo.toml}}
```
-If the author information that Cargo obtained from your environment is not
-correct, fix that in the file and save it again.
+Si la información del autor que Cargo ha obtenido de tu entorno no es
+correcta, arréglalo en el archivo y guárdalo
-As you saw in Chapter 1, `cargo new` generates a “Hello, world!” program for
-you. Check out the *src/main.rs* file:
+Cómo viste en el capítulo 1, `cargo new` genera un “!Hola, mundo!” para tí.
+Comprueba el archivo *src/main.rs*:
-Filename: src/main.rs
+Nombre del archivo: src/main.rs
```rust
{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/src/main.rs}}
```
-Now let’s compile this “Hello, world!” program and run it in the same step
-using the `cargo run` command:
+Ahora vamos a compilar este programa de “¡Hola, mundo!” y ejecutémoslo en el
+mismo paso utilizando `cargo run`:
```console
{{#include ../listings/ch02-guessing-game-tutorial/no-listing-01-cargo-new/output.txt}}
```
-The `run` command comes in handy when you need to rapidly iterate on a project,
-as we’ll do in this game, quickly testing each iteration before moving on to
-the next one.
+El comando `run` es muy útil cuando necesitas iterar rápidamente en un proyecto,
+tal y cómo vamos a hacer en este juego, testeando rápidamente cada iteración
+antes de ir a la siguiente.
-Reopen the *src/main.rs* file. You’ll be writing all the code in this file.
+Vuelve a abrir el archivo *src/main.rs*. Vas a escribir todo el código en este
+archivo.
-## Processing a Guess
+## Procesando una predicción
-The first part of the guessing game program will ask for user input, process
-that input, and check that the input is in the expected form. To start, we’ll
-allow the player to input a guess. Enter the code in Listing 2-1 into
-*src/main.rs*.
+La primera parte del juego de predicciones será preguntar al usuario por ella,
+procesarla y comprobar que la respuesta tiene el formato adecuado. Para empezar,
+permitiremos al jugador introducir una predicción. Escribe el código del listado
+2-1 en *src/main.rs*.
-Filename: src/main.rs
+Nombre del archivo: src/main.rs
```rust,ignore
{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:all}}
```
-Listing 2-1: Code that gets a guess from the user and
-prints it
+Listado 2-1: Código que obtiene una predicción del usuario
+y la imprime
-This code contains a lot of information, so let’s go over it line by line. To
-obtain user input and then print the result as output, we need to bring the
-`io` (input/output) library into scope. The `io` library comes from the
-standard library (which is known as `std`):
+Este código tiene mucha información, así que vamos línea por línea. Para obtener
+la entrada del usuario y luego imprimir el resultado, necesitamos importar la
+librería `io` (input/output, en español, entrada/salida) en este ámbito. La
+libería `io` viene de la librería estándar (que es cónocida cómo `std`):
```rust,ignore
{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:io}}
```
-By default, Rust brings only a few types into the scope of every program in
-[the *prelude*][prelude]. If a type you want to use isn’t in the
-prelude, you have to bring that type into scope explicitly with a `use`
-statement. Using the `std::io` library provides you with a number of useful
-features, including the ability to accept user input.
+Por defecto, Rust trae solo unos pocos tipos al ámbito en [el *preludio*][prelude] .
+Si un tipo que quieres no está en el preludio, tienes que traer ese tipo al
+ámbito de manera explícita con la declaración `use`. Utilizar la librería
+`std::io` te da numerosas características útiles, incluyendo la habilidad
+para aceptar entrada del usuario.
[prelude]: ../std/prelude/index.html
-As you saw in Chapter 1, the `main` function is the entry point into the
-program:
+Cómo viste en el capítulo 1, la función `main` es el punto de entrada al
+programa:
```rust,ignore
{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:main}}
```
-The `fn` syntax declares a new function, the parentheses, `()`, indicate there
-are no parameters, and the curly bracket, `{`, starts the body of the function.
+La sintaxis `fn` declara una nueva función, los parentesis `()`, indican que no
+hay parámetros, y la llave `{`, inicia el cuerpo de la función.
-As you also learned in Chapter 1, `println!` is a macro that prints a string to
-the screen:
+Cómo también aprendiste en el capítulo 1, `println!` es una macro que imprime una
+cadena de texto en pantalla:
```rust,ignore
{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:print}}
```
-This code is printing a prompt stating what the game is and requesting input
-from the user.
+Este código está imprimiendo una solicitud diciendo que es el juego y solicitando
+entrada por parte del usuario.
-### Storing Values with Variables
+### Almacenando valores con variables
-Next, we’ll create a place to store the user input, like this:
+Ahora, crearemos un lugar dónde almacenar la entrada del usuario, cómo este:
```rust,ignore
{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:string}}
```
-Now the program is getting interesting! There’s a lot going on in this little
-line. Notice that this is a `let` statement, which is used to create a
-*variable*. Here’s another example:
+¡Ahora el programa se está poniendo interesante! Hay mucho ocurriendo en está
+pequeña línea. Nota cómo esto esto es una declaración `let`, que se utiliza para
+crear una *variable*. Aquí otro ejemplo:
```rust,ignore
let foo = bar;
```
-This line creates a new variable named `foo` and binds it to the value of the
-`bar` variable. In Rust, variables are immutable by default. We’ll be
-discussing this concept in detail in the [“Variables and
-Mutability”][variables-and-mutability] section in Chapter 3.
-The following example shows how to use `mut` before the variable name to make
-a variable mutable:
+Esta línea crea una nueva variable llamada `foo` y la une al valor de la variable
+`bar`. En Rust, la variables son inmutables por defecto. Trataremos esto en más
+detalle en la sección del capítulo 3 ["Variables y mutabilidad"][variables-and-mutability]
+. El siguiente ejemplo muestra cómo utilizar `mut` antes del nombre
+de la variable para hacer una variable mutable:
```rust,ignore
-let foo = 5; // immutable
+let foo = 5; // inmutable
let mut bar = 5; // mutable
```
+> Nota: La sintaxis `//` comienza un comentario hasta el final de la línea.
+> Rust ignora todo lo que haya en comentario, que se discutirán en más detalle
+> en el capítulo 3.
-> Note: The `//` syntax starts a comment that continues until the end of the
-> line. Rust ignores everything in comments, which are discussed in more detail
-> in Chapter 3.
-
-Let’s return to the guessing game program. You now know that `let mut guess`
-will introduce a mutable variable named `guess`. On the other side of the equal
-sign (`=`) is the value that `guess` is bound to, which is the result of
-calling `String::new`, a function that returns a new instance of a `String`.
-[`String`][string] is a string type provided by the standard
-library that is a growable, UTF-8 encoded bit of text.
+Ahora volvamos al programa del juego de predicciones. Ahora ya sabes que
+`let mut prediccion` introducirá en el programa una variable mutable llamada
+`guess`. En el otro lado de la igualdad (`=`) está el valor al que `guess` está
+atado, que es el resultado de llamar a `String::new`, una función que devuelve
+una nueva instancia de `String` (cadena de texto, en español). [`String`][string]
+es un tipo de cadena de texto que da la librería estándar que es un trocito de
+texto expandible y codificado en UTF-8
[string]: ../std/string/struct.String.html
-The `::` syntax in the `::new` line indicates that `new` is an *associated
-function* of the `String` type. An associated function is implemented on a type,
-in this case `String`, rather than on a particular instance of a `String`. Some
-languages call this a *static method*.
+La sintaxis `::` en `::new` indica que `new` es una *función asociada* al tipo
+`String`. Una función asociada es implementada en un tipo, en este caso `String`,
+en vez de en una instancia en particular de `String`. Algunos lenguajes llaman a
+esto un *método estático*.
-This `new` function creates a new, empty string. You’ll find a `new` function
-on many types, because it’s a common name for a function that makes a new value
-of some kind.
+Esta función `new` crea una cadena de texto nueva y vacía. Encontrarás una
+función `new` en muchos tipos, porque es un nombre común para una función que
+crea un nuevo valor de algún tipo.
-To summarize, the `let mut guess = String::new();` line has created a mutable
-variable that is currently bound to a new, empty instance of a `String`. Whew!
+Pra resumir, la línea `let mut guess = String::new();` a creado una variable
+mutable que está asignada a una nueva instancia vacía de `String`. ¡Guau!
-Recall that we included the input/output functionality from the standard
-library with `use std::io;` on the first line of the program. Now we’ll call
-the `stdin` function from the `io` module:
+Recuerda que hemos incluido la funcionalidad de la entrada/salida de la librería
+estándar con `use std::io;` en la primera línea del programa. Ahora llamaremos a
+la función `stdin` desde el módulo `io`:
```rust,ignore
{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:read}}
```
-If we hadn’t put the `use std::io` line at the beginning of the program, we
-could have written this function call as `std::io::stdin`. The `stdin` function
-returns an instance of [`std::io::Stdin`][iostdin], which is a
-type that represents a handle to the standard input for your terminal.
+Si no hubieramos puesto la línea `use std::io` en el principio del programa,
+podríamos haber escrito la llamada a la función cómo `std::io::stdin`. La
+función `stdin` devuelve una instancia de [`std::io::Stdin`][iostdin] ,
+que es un tipo que representa una manilla a la entrada estándar para tu terminal.
[iostdin]: ../std/io/struct.Stdin.html
-The next part of the code, `.read_line(&mut guess)`, calls the
-[`read_line`][read_line] method on the standard input handle to
-get input from the user. We’re also passing one argument to `read_line`: `&mut
-guess`.
+La siguiente parte del código, `.read_line(&mut guess)`, llama
+al método ['read_line`][read_line] en la manilla de la entrada
+estándar para conseguir entrada por parte del usuario. También estamos pasando
+un argumento a `read_line`: `&mut guess`.
[read_line]: ../std/io/struct.Stdin.html#method.read_line
-The job of `read_line` is to take whatever the user types into standard input
-and append that into a string (without overwriting its contents), so it takes
-that string as an argument. The string argument needs to be mutable so the
-method can change the string’s content by adding the user input.
+El trabajo de `read_line` es capturar lo que el usuario escriba en la entrada
+estándar y añadirlo en una cadena de texto (sin sobreescribir sus contenidos),
+así que toma una cadena de texto cómo un argumento. El argumento de la cadena
+de texto necesita ser mutable para el que método pueda cambiar el contenido de
+la cadena añadiendo la entrada del usuario.
-The `&` indicates that this argument is a *reference*, which gives you a way to
-let multiple parts of your code access one piece of data without needing to
-copy that data into memory multiple times. References are a complex feature,
-and one of Rust’s major advantages is how safe and easy it is to use
-references. You don’t need to know a lot of those details to finish this
-program. For now, all you need to know is that like variables, references are
-immutable by default. Hence, you need to write `&mut guess` rather than
-`&guess` to make it mutable. (Chapter 4 will explain references more
-thoroughly.)
+El `&` indica que este argumento es una *referencia*, lo que permite que varias
+partes de tu código accedan a la misma información sin necesitar copiar esta
+información en memoria múltiples veces. Las refencias son una característica
+compleja, y una de las mayores ventajas de Rust en cómo de seguro y sencillo es
+utilizar referencias. No necesitar saber muchos detalles para terminar este programa.
+Por ahora, todo lo que necesitas saber es que cómo las variables, las referencias
+son inmutables por defecto. Por lo tanto, tienes que escribir `&mut guess` en vez
+de `&guess` para hacerlo mutable. (En el capítulo 4 se explicarán las referencias
+con mayor profundidad).
-### Handling Potential Failure with the `Result` Type
+### Manejar posibles fallos con el tipo `Result`
-We’re still working on this line of code. Although we’re now discussing a third
-line of text, it’s still part of a single logical line of code. The next part
-is this method:
+Todavía estamos trabajando en la misma línea de código. Aunque estemos discutiendo
+una tercera línea de texto, todavía es parte de la misma línea lógica de código. La
+siguiente parte este mmétodo:
```rust,ignore
{{#rustdoc_include ../listings/ch02-guessing-game-tutorial/listing-02-01/src/main.rs:expect}}
```
-When you call a method with the `.foo()` syntax, it’s often wise to introduce a
-newline and other whitespace to help break up long lines. We could have
-written this code as:
+Cuándo llamas al método con la sinxtaxis `.foo()`, puede ser una decisión sabia
+introducir una nueva línea y un espacio en blanco para poder romper líneas largas.
+Podríamos haber escrito este código de la siguiente manera:
```rust,ignore
-io::stdin().read_line(&mut guess).expect("Failed to read line");
+io::stdin().read_line(&mut prediccion).expect("Lectura de la línea fallida");
```
-However, one long line is difficult to read, so it’s best to divide it. Now
-let’s discuss what this line does.
+Sin embargo, una línea larga es difícil de leer, así que es mejor dividirla. Ahora,
+hablemos de lo que hace esta línea.
-As mentioned earlier, `read_line` puts what the user types into the string
-we’re passing it, but it also returns a value—in this case, an
-[`io::Result`][ioresult]. Rust has a number of types named
-`Result` in its standard library: a generic [`Result`][result]
-as well as specific versions for submodules, such as `io::Result`.
+Cómo mencionamos antes, `read_line` pone lo que haya escrito el usuario en
+la cadena de texto que le hayamos pasado, pero también retorna un valor en
+este caso, un [`io::Result`][ioresult]. Rust tiene un número
+de tipos llamados `Result` en su librería estándar: un [`Result`][result]
+así cómo versiones específicas para submódulos, cómo `io::Result`.
[ioresult]: ../std/io/type.Result.html
[result]: ../std/result/enum.Result.html
-The `Result` types are [*enumerations*][enums], often referred
-to as *enums*. An enumeration is a type that can have a fixed set of values,
-and those values are called the enum’s *variants*. Chapter 6 will cover enums
-in more detail.
+Los tipos `Result` son [*enumeraciones*][enums], comúnmente llamadas
+cómo *enums*. Una enumeración es un tipo que puede tener un conjunto fijo de
+valores, y todos esos valores se llaman las *variantes* de la enum. El capítulo 6
+cubrirá las enums en más detalle.
[enums]: ch06-00-enums.html
-For `Result`, the variants are `Ok` or `Err`. The `Ok` variant indicates the
-operation was successful, and inside `Ok` is the successfully generated value.
-The `Err` variant means the operation failed, and `Err` contains information
-about how or why the operation failed.
-
-The purpose of these `Result` types is to encode error-handling information.
-Values of the `Result` type, like values of any type, have methods defined on
-them. An instance of `io::Result` has an [`expect` method][expect] that you can call. If this instance of `io::Result` is an `Err` value,
-`expect` will cause the program to crash and display the message that you
-passed as an argument to `expect`. If the `read_line` method returns an `Err`,
-it would likely be the result of an error coming from the underlying operating
-system. If this instance of `io::Result` is an `Ok` value, `expect` will take
-the return value that `Ok` is holding and return just that value to you so you
-can use it. In this case, that value is the number of bytes in what the user
-entered into standard input.
+Para `Result`, las variantes son `Ok` o `Err`. La variante `Ok` indica que la
+operación fue exitosa, y dentro de `Ok` está el valor generado. La variante
+`Err` significa que la operación ha fallado, y `Err` contiene la información
+sobre cómo o por qué la operación falló.
+
+El propósito de estos tipos `Result` es codificar la información para el manejo
+de los errores. Los valores del tipo `Result`, cómo los valores de cualquier tipo,
+tienen métodos definidos en ellos. Una instancia de `io::Result` tiene un
+[método `expect`][expect] que puedes llamar. Si esta instancia de
+`io::Result` es un valor `Err`, `expect` hará que el programa se estrelle y
+mostrará el mensaje que pasaste cómo argumento. Si el método `read_line`
+devuelve un valor `Err`, es probable que el error venga del sistema operativo
+subyacente. Si esta instancia de `io::Result` es un valor `Ok`, `expect` tomará el
+valora que `Ok` está almacenando y devolverá ese valor para que puedas utilizarlo.
+En este caso, el valor es el número de bytes que en los que el usuario introdujo en
+la entrada estándar.
[expect]: ../std/result/enum.Result.html#method.expect
-If you don’t call `expect`, the program will compile, but you’ll get a warning:
+Si no llamases a `expect`, el programa compilaría, pero tendrías una advertencia:
```console
{{#include ../listings/ch02-guessing-game-tutorial/no-listing-02-without-expect/output.txt}}
```
-Rust warns that you haven’t used the `Result` value returned from `read_line`,
-indicating that the program hasn’t handled a possible error.
+Rust advierto que no has usado el valor `Result` devuelto desde `read_line`,
+indicando que el programa no ha manejado un posible error.
-The right way to suppress the warning is to actually write error handling, but
-because you just want to crash this program when a problem occurs, you can use
-`expect`. You’ll learn about recovering from errors in Chapter 9.
+La manera correcta de quitar esta advertencia es manejar el error de verdad, pero
+cómo simplemente quieres que tu programa se estrelle cuando ocurra un problema,
+puedes usar `expect`. Aprenderás sobre recuperación de errores en el capítulo 9.
### Printing Values with `println!` Placeholders
diff --git a/src/ch03-00-common-programming-concepts.md b/src/ch03-00-common-programming-concepts.md
index 801ecc3c34..c565b88180 100644
--- a/src/ch03-00-common-programming-concepts.md
+++ b/src/ch03-00-common-programming-concepts.md
@@ -1,23 +1,23 @@
-# Common Programming Concepts
+# Conceptos fundamentales de programación
-This chapter covers concepts that appear in almost every programming language
-and how they work in Rust. Many programming languages have much in common at
-their core. None of the concepts presented in this chapter are unique to Rust,
-but we’ll discuss them in the context of Rust and explain the conventions
-around using these concepts.
+Este capítulo cubre conceptos que aparecen en casi todos los lenguajes de programación
+y cómo funcionan en Rust. Muchos lenguajes de programación tienen mucho en común en
+su núcleo. Ninguno de los conceptos presentados en este capítulo es exclusivo de Rust,
+pero los discutiremos en el contexto de Rust y explicaremos las convenciones
+sobre el uso de estos conceptos.
-Specifically, you’ll learn about variables, basic types, functions, comments,
-and control flow. These foundations will be in every Rust program, and learning
-them early will give you a strong core to start from.
+En concreto, aprenderás sobre variables, tipos básicos, funciones, comentarios
+y el flujo de control. Estos fundamentos estarán en cada programa de Rust, y aprenderlos
+y aprenderlos desde el principio te dará un núcleo fuerte del que partir.
-> #### Keywords
+> #### Palabras clave
>
-> The Rust language has a set of *keywords* that are reserved for use by
-> the language only, much as in other languages. Keep in mind that you cannot
-> use these words as names of variables or functions. Most of the keywords have
-> special meanings, and you’ll be using them to do various tasks in your Rust
-> programs; a few have no current functionality associated with them but have
-> been reserved for functionality that might be added to Rust in the future. You
-> can find a list of the keywords in [Appendix A][appendix_a].
+> El lenguaje Rust tiene un conjunto de *palabras clave* que están reservadas para su uso
+> el lenguaje solamente, como en otros lenguajes. Tenga en cuenta que no puede
+> usar estas palabras como nombres de variables o funciones. La mayoría de las palabras clave tienen
+> La mayoría de las palabras clave tienen significados especiales, y las usará para hacer varias tareas en sus programas de Rust.
+> programas de Rust; unas pocas no tienen una funcionalidad actual asociada a ellas, sino que han sido
+> Algunas no tienen una funcionalidad actual asociada a ellas, sino que han sido reservadas para una funcionalidad que podría ser añadida a Rust en el futuro. En
+> puede encontrar una lista de las palabras clave en el [Apéndice A][appendix_a].
[appendix_a]: appendix-01-keywords.md
diff --git a/src/foreword.md b/src/foreword.md
index 2265e27142..51f0d04471 100644
--- a/src/foreword.md
+++ b/src/foreword.md
@@ -1,41 +1,41 @@
-# Foreword
+# Prólogo
-It wasn’t always so clear, but the Rust programming language is fundamentally
-about *empowerment*: no matter what kind of code you are writing now, Rust
-empowers you to reach farther, to program with confidence in a wider variety of
-domains than you did before.
+No siempre fue tan claro, pero el lenguaje de programación Rust es fundamentalmente
+de la capacitación: no importa qué tipo de código estés escribiendo ahora, Rust te permite llegar más lejos, programar con confianza en una variedad más amplia de
+Rust te permite llegar más lejos, programar con confianza en una mayor variedad de
+de dominios que antes.
-Take, for example, “systems-level” work that deals with low-level details of
-memory management, data representation, and concurrency. Traditionally, this
-realm of programming is seen as arcane, accessible only to a select few who
-have devoted the necessary years learning to avoid its infamous pitfalls. And
-even those who practice it do so with caution, lest their code be open to
-exploits, crashes, or corruption.
+Por ejemplo, el trabajo "a nivel de sistemas" que se ocupa de los detalles de bajo nivel de
+gestión de la memoria, la representación de los datos y la concurrencia. Tradicionalmente, este
+tradicionalmente, este ámbito de la programación se considera arcano, accesible sólo para unos pocos
+han dedicado los años necesarios para aprender a evitar sus trampas infames. Y
+Y hasta los que lo practican lo hacen con precaución, para que su código no se preste a
+exploits, fallos o corrupción.
-Rust breaks down these barriers by eliminating the old pitfalls and providing a
-friendly, polished set of tools to help you along the way. Programmers who need
-to “dip down” into lower-level control can do so with Rust, without taking on
-the customary risk of crashes or security holes, and without having to learn
-the fine points of a fickle toolchain. Better yet, the language is designed to
-guide you naturally towards reliable code that is efficient in terms of speed
-and memory usage.
+Rust rompe estas barreras eliminando las antiguas barreras y proporcionando un conjunto de
+un conjunto de herramientas amigables y pulidas para ayudarte en el camino. Los programadores que necesitan
+que necesitan "sumergirse" en el control de bajo nivel pueden hacerlo con Rust, sin
+el riesgo habitual de fallos o agujeros de seguridad, y sin tener que aprender
+los puntos finos de una cadena de herramientas inconstante. Mejor aún, el lenguaje está diseñado para
+guiarte de forma natural hacia un código fiable y eficiente en términos de velocidad
+velocidad y uso de memoria.
-Programmers who are already working with low-level code can use Rust to raise
-their ambitions. For example, introducing parallelism in Rust is a relatively
-low-risk operation: the compiler will catch the classical mistakes for you. And
-you can tackle more aggressive optimizations in your code with the confidence
-that you won’t accidentally introduce crashes or vulnerabilities.
+Los programadores que ya trabajan con código de bajo nivel pueden utilizar Rust para aumentar
+sus ambiciones. Por ejemplo, introducir el paralelismo en Rust es una operación relativamente
+riesgo: el compilador detectará los errores clásicos por ti. Y en
+puedes abordar optimizaciones más agresivas en tu código con la confianza
+de que no introducirás accidentalmente cuelgues o vulnerabilidades.
-But Rust isn’t limited to low-level systems programming. It’s expressive and
-ergonomic enough to make CLI apps, web servers, and many other kinds of code
-quite pleasant to write — you’ll find simple examples of both later in the
-book. Working with Rust allows you to build skills that transfer from one
-domain to another; you can learn Rust by writing a web app, then apply those
-same skills to target your Raspberry Pi.
+Pero Rust no se limita a la programación de sistemas de bajo nivel. Es lo suficientemente expresivo y
+lo suficientemente flexible como para hacer que las aplicaciones CLI, los servidores web y muchos otros tipos de código sean bastante agradables de escribir.
+bastante agradable de escribir - encontrarás ejemplos sencillos de ambos más adelante en el
+libro. Trabajar con Rust te permite construir habilidades que se transfieren de un dominio a otro.
+de un dominio a otro; puedes aprender Rust escribiendo una aplicación web, y luego aplicar esas
+mismas habilidades para apuntar a tu Raspberry Pi.
-This book fully embraces the potential of Rust to empower its users. It’s a
-friendly and approachable text intended to help you level up not just your
-knowledge of Rust, but also your reach and confidence as a programmer in
-general. So dive in, get ready to learn—and welcome to the Rust community!
+Este libro aprovecha al máximo el potencial de Rust para potenciar a sus usuarios. Es un texto
+texto amigable y accesible que pretende ayudarte a subir de nivel no sólo en tu
+conocimiento de Rust, sino también su alcance y confianza como programador en
+programador en general. Así que sumérgete, prepárate para aprender y ¡bienvenido a la comunidad Rust!
-— Nicholas Matsakis and Aaron Turon
+— Nicholas Matsakis and Aaron Turon
\ No newline at end of file
diff --git a/src/title-page.md b/src/title-page.md
index c7b3d673f7..8ab819050c 100644
--- a/src/title-page.md
+++ b/src/title-page.md
@@ -1,16 +1,16 @@
-# The Rust Programming Language
+# Lenguaje de programación Rust
-*by Steve Klabnik and Carol Nichols, with contributions from the Rust Community*
+*por Steve Klabnik y Carol Nichols, con contribuciones de la comunidad de la roya*
-This version of the text assumes you’re using Rust 1.50 or later with
-`edition="2018"` in *Cargo.toml* of all projects to use Rust 2018 Edition
-idioms. See the [“Installation” section of Chapter 1][install]
-to install or update Rust, and see the new [Appendix E][editions] for information on editions.
+Esta versión del texto asume que estás usando Rust 1.50 o posterior con
+`edición="2018"` en *Cargo.toml* de todos los proyectos para usar Rust 2018 Edition
+de Rust. Ver la sección ["Instalación" del capítulo 1][install]
+para instalar o actualizar Rust, y ver el nuevo [Apéndice E][editions] para obtener información sobre las ediciones.
-The 2018 Edition of the Rust language includes a number of improvements that
-make Rust more ergonomic and easier to learn. This iteration of the book
-contains a number of changes to reflect those improvements:
+La edición 2018 del lenguaje Rust incluye una serie de mejoras que
+hacen que Rust sea más ergonómico y fácil de aprender. Esta iteración del libro
+contiene una serie de cambios para reflejar esas mejoras:
- Chapter 7, “Managing Growing Projects with Packages, Crates, and Modules,”
has been mostly rewritten. The module system and the way paths work in the