flakolefluk.dev

Aprendiendo Rust en público - Variables (4)

Bienvenidos a la última parte de la serie de ejercicios sobre variables en Rust.

Ejercicio 5 #

Revisemos el código inicial...

fn main() {
let number = "T-H-R-E-E";
println!("Spell a Number : {}", number);
number = 3;
println!("Number plus two is : {}", number + 2);
}

e inmediatamente veamos el error

⚠️  Compiling of exercises/variables/variables5.rs failed! Please try again. Here's the output:
error[E0308]: mismatched types
--> exercises/variables/variables5.rs:9:14
|
9 | number = 3;
| ^ expected `&str`, found integer

error[E0369]: cannot add `{integer}` to `&str`
--> exercises/variables/variables5.rs:10:48
|
10 | println!("Number plus two is : {}", number + 2);
| ------ ^ - {integer}
| |
| &str
|
= note: an implementation of `std::ops::Add` might be missing for `&str`

error: aborting due to 2 previous errors

Some errors have detailed explanations: E0308, E0369.
For more information about an error, try `rustc --explain E0308`.

La variable number no declara un tipo en particular, pero inicialmente se le asigna el valor T-H-R-E-E. El compilador infiere entonces el tipo de la variable, en este caso y como indica el error, &str.
Entonces, el primer error sería que a una variable de tipo &str, luego le asignamos el valor 3.
Como en la línea 10 esperamos realizar una suma, haremos que la variable sea siempre un número y así evitar cambiar el tipo de la variable.
El ejercicio contiene otro error, pero dejaremos que el compilador nos de una mano.

El ejercicio quedaría entonces así:

fn main() {
let number = 1;
println!("Spell a Number : {}", number);
number = 3;
println!("Number plus two is : {}", number + 2);
}

Ahora nos aparece un nuevo error, que ya vimos anteriormente.

⚠️  Compiling of exercises/variables/variables5.rs failed! Please try again. Here's the output:
error[E0384]: cannot assign twice to immutable variable `number`
--> exercises/variables/variables5.rs:9:5
|
7 | let number = 1;
| ------
| |
| first assignment to `number`
| help: make this binding mutable: `mut number`
8 | println!("Spell a Number : {}", number);
9 | number = 3;
| ^^^^^^^^^^ cannot assign twice to immutable variable

error: aborting due to previous error

For more information about this error, try `rustc --explain E0384`.

En Rust, las variables son inmutables a menos que explicitamente lo expresemos.
Para hacer nuestra variable mutable, basta con agregar la palabara mut cuando la declaramos.

Finalmente nuestro ejercicio quedaría así:




El código corregido quedaría así.

```rust
fn main() {
let mut x = 3;
println!("Number {}", x);
x = 5; // don't change this line
println!("Number {}", x);
}

Hemos completado el ejercicio!

Ejercicio 6 #

Hemos llegado al último ejercicio de variables de nuestra serie.

const NUMBER = 3;
fn main() {
println!("Number {}", NUMBER);
}

El compilador nos dará las pistas para arreglar este ejercicio.

⚠️  Compiling of exercises/variables/variables6.rs failed! Please try again. Here's the output:
error: missing type for `const` item
--> exercises/variables/variables6.rs:6:7
|
6 | const NUMBER = 3;
| ^^^^^^ help: provide a type for the item: `NUMBER: i32`

error: aborting due to previous error

La solución la encontramos en el capítulo 3.1 del libro de rust:
Una constante const debe siempre indicar explícitamente el tipo de variable.

Luego, el problema lo resolvemos dandole a la constante para la que el valor 3 sea válido, por ejemplo i32.

const NUMBER: i32 = 3;
fn main() {
println!("Number {}", NUMBER);
}

Hemos completado la serie de ejercicios de variables. Felicidades.

Un breve resumen de lo aprendido:

Para seguir esta serie, puedes buscar por el tag #aprendiendo_rust