Inicia tu camino con Rust
Bienvenida al Curso Básico de Rust
Rust: un lenguaje amado por los desarrolladores
Instalando Rust en MacOS o Linux
Instalando Rust en Windows
Domina las bases de Rust
Creando un nuevo proyecto en Rust
Variables de Rust y cómo mostrarlas en pantalla
Recibiendo datos del usuario
Condicionales
Ciclo Loop
Primer proyecto: calculadora digital
Descripción del proyecto
Cargo (dependencias)
¿Qué significa unwrap?
Creando nuestra calculadora
Estructuras y funciones en Rust
Arrays y Ciclo For en Rust
Las funciones en Rust
Segundo proyecto: videojuego de texto
Descripción del proyecto: videojuego de texto
Creación y descripción del entorno
Estructuras básicas, narrativa y opciones de Rust
Interacción con el entorno y datos del usuario
Esto es solo el comienzo
Únete a la comunidad, Rustacean
You don't have access to this class
Keep learning! Join and start boosting your career
Enabling user interaction with your application is one of the foundations of any programming language. Rust facilitates communication through the command line interface. Let's see how to achieve it:
To receive data from the user, you have to make use of some internal Rust libraries that access the operating system and allow the user to input data via the console.
fn main() { println!("Enter your name:"); let mut name: String = String::new(); std::io::stdin().read_line(&mut name).unwrap(); name = name.trim().to_string(); println!("Welcome: {}", name); }
If you have experience in languages like C++ or Java, you may be more familiar with some concepts or reserved words. Let's see what each line of code is and how it works:
println!("Enter your name:");
A simple console message to prompt the user for the name.let mut name: String = String::new();
We declare a string variable where we will store the name. Note that you can declare a string with String or with &str. The differences are minimal, the first one allows you to manipulate the text, make substrings or splits, but it occupies some more space in memory. The second is plain text with no other functionality.std::io::stdin().read_line(&mut name).unwrap();
The most complicated line, std is a Rust library to access the operating system. io means inputs/outputs, println!() uses it internally to show messages by console, here we will use it to enter data by the same one. stdin() allows to bring information and read_line() indicates that this information will be received by console. &mut name is the variable where we will store the data entered by the user (use mut in the variables to indicate that it will change value). Finally, unwrap(), helps us with error handling.name = name.trim().to_string();
Here we just format the text to eliminate line breaks and whitespace.println!("Welcome: {}", name);
After the user enters his name, we show it in the console.Remember that you can execute the code with the cargo run
command.
By default, all the data that the user enters by console is of type string. It may happen that you need integers and for this you have to convert the data type as follows:
fn main() { println!("Enter your age:"); let mut age: String = String::new(); std::io::stdin().read_line(&mut age).unwrap(); let age_int: u8 = age.trim().parse().unwrap(); println!("The age is: {}", age_int); }
The important thing here is the let
line age_int: u8 = age.trim().parse().unwrap();
where we create a new variable where we will store a number of type u8. This way you will be able to manipulate that data and perform any mathematical operation.
Up to here, you already know how to declare several types of variables, receive and display data by console. Play with these tools creating a form so that the user enters values by console and can manipulate them before showing them by the terminal.
Contributed by: Kevin Fiorentino.
Contributions 68
Questions 7
Pequeño dato, Rust tiene como estandar usar snake case para declaraciones, en caso de que no la utilices te lo señalizara como un warning en tiempo de compilacion.
fn main() {
// snake case work fine
let var_en_snake_case: u8 = 8 ;
//Camel Case, Warning in compilation time
let varEnCamelCase: u8 = 8;
}
Quería comprender por qué era necesario usar unwrap
en algunas líneas del ejercicio de la clase. Así que comencé a leer sobre dicha función y resulta que la mayoría de las operaciones para entrada o salida devuelven el tipo Result<T, E>
, el cual es un tipo que suele ser usado para retornar y propagar errores. Es un enum
con las variantes, Ok(T)
, para representar el caso de éxito y contiene un valor, y Err(E)
, el cual representa que ocurrió un error y contiene el valor de dicho error.
enum Result<T, E> {
Ok(T),
Err(E),
}
Una vez entendido esto, unwrap
lo que hace es extraer el valor en caso de éxito, pero, dado que en la operación de entrada o salida podemos obtener un error, la documentación oficial desaconseja su uso. En vez de ello, aconsejan usar pattern matching para manejar el caso de error de manera explícita o hacer uso de unwrap_or
, unwrap_or_else
, unwrap_or_default
.
También existen otras alternativas como expect
, la cual he visto en otras soluciones acá en la sección de comentarios.
Entonces, basado en esta parte del código de la clase:
println!("age: ");
let mut age : String = String::new();
std::io::stdin().read_line(&mut age).unwrap();
let age_as_integer : u8 = age.trim().parse().unwrap();
println!("Hey {name}, with {age_as_integer} years old");
Podríamos reemplazar un poco el código usando pattern matching para evitar casos de error como el siguiente:
age:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: Empty }', src/main.rs:12:50
que podrían llegar a ser un poco crípticos. En este caso, el usuario (yo), introdujo un valor vacío por edad.
println!("age: ");
let mut age : String = String::new();
match std::io::stdin().read_line(&mut age) {
Ok(n) if n > 1 => {
let age_as_integer : u8 = age.trim().parse().expect("expected a positive number");
println!("Hey {name}, with {age_as_integer} years old";
}
Ok(_) => {
println!("error: age value cannot be empty")
}
Err(error) => println!("error: {error}")
};
En este caso capturo n
, el cual es el número de bytes leídos, y si dicho valor no es mayor a 1 pues muestro un error más ameno al usuario. Para este ejemplo el manejo explícito por medio de pattern matching no parece añadir
mayor ruido, incluso, si este bloque de código estuviese dentro de una función específica, después de mostrar el mensaje de error podría llamarse a si misma para darle otro intento al usuario. Sin embargo, supongo que en aplicaciones
más largas el manejo explícito de errores por medio de match
puede volverse tedioso, y allí, si es más conveniente usar otros helpers como expect
o los menciones previamente.
Se puede desestructurar las librerias importanto solo el componente que se va a utilizar con la palabra reservada use
use std::io;
fn main() {
println!(
"Hello {}, you have {} years old!",
&get_name_from_user(),
&get_age_from_user()
);
}
fn get_name_from_user() -> String {
println!("Please insert your name");
let mut name = String::new();
io::stdin()
.read_line(&mut name)
.expect("Failed to read line");
name.trim().to_string()
}
fn get_age_from_user() -> u8 {
println!("Please insert your age");
let mut age = String::new();
io::stdin()
.read_line(&mut age)
.expect("Failed to read line");
age.trim().parse().unwrap()
}
También se puede importar stdin para evitar llamarlo desde std cada vez que querramos usarlo, ejemplo:
use std::io::stdin;
fn main() {
let mut name: String = String::new();
println!("Ingrese su nombre:");
stdin().read_line(&mut name).unwrap();
}
Hola! fui comentando la explicacion de cada funcion, quizas les sirva
// mut --> para que pueda ser editable con las distintas ejecuciones
// = String::new() --> string vacio
let mut name: String = String::new();
/* --> para el ingreso de datos
* std --> libreria standard de rust
* io --> input and output
* stdin() --> fn para el ingreso de datos
* read_line(name) --> leer datos desde la consola que se van a guardar en name
* unwrap() --> para el manejo de errores */
std::io::stdin().read_line(&mut name).unwrap();
/*
* trim() --> para que quede mostrado en una linea en consola
* to_string() --> castea a string
*/
name = name.trim().to_string();
print!("Enter your lastname please: ");
let mut lastname: String = String::new();
std::io::stdin().read_line(&mut lastname).unwrap();
lastname = lastname.trim().to_string();
print!("Enter your age please: ");
let mut age: String = String::new();
std::io::stdin().read_line(&mut age).unwrap();
/*
* se puede poner cualquier cosa como edad
* parse() --> convierte el string a numero borrando lo que no sea
* unwrap() --> maneja errores
*/
let age_int : u8 = age.trim().parse().unwrap();
println!("Hi {} {}. Your age is {} years.", name, lastname, age_int);
Pequeño aporte ya que antes de hacer el curso leí un pequeño libro de rust
https://goyox86.gitbooks.io/el-libro-de-rust/content/index.html
Rust tiene 3 formas
&str => es una referencia a un literal de cadena.
El literal de cadena también se conoce como un segmento de cadena. Esto se debe a que a &str se refiere a una parte de una cadena.
String => es una instancia de la estructura de String
Una distinción importante entre los dos es que** &str** se almacena en la pila, y String se asigna a la pila. Esto significa que el valor de &str no puede cambiar, y su tamaño es fijo, mientras que String puede tener un tamaño desconocido en tiempo de compilación.
El tercer tipo es:
char es un USV (Valor Escalar Unicode), que se representa en unicode con valores como U+221E, el unicode para ‘∞’.
Saludos.
fn main() {
let mut country: String = String::new();
println!("Where are you from?");
std::io::stdin().read_line(&mut country).unwrap();
match country.as_str().trim() {
"chile" => println!("Hola po!"),
"peru" => println!("Hola pe!"),
"argentina" => println!("Hola che!"),
"brazil" => println!("Oi, tudo bem?"),
_ => println!("Hello world"),
}
}
La lista podria crecer…
Enteros con signo (Desde i8 hasta i128)
También tenemos los números sin signos, para estos números tenemos el doble de tamaño(hacia la derecha).
Un ejemplo para que se entienda mejor:
fn main(){
// el rango de un numero entero con signo abarca desde -127 hasta 127
let temp_sign: i8 = -30; // tranquilo, no va a explotar.
// el rango de un numero sin signo es mayor debido a que ya no tenemos los numeros con signo.
let temp_usign: u8 = 255; // aqui puede que explote si usas un signo.
println!("temperatura {} {}", temp_sign, temp_usign);
}
Enteros sin signo (Desde u8 hasta u128)
Espero que hayan entendido un poco sobre esto, Rust tiene muchos de datos que espero nos muestren pronto en el curso :p
Quise de una vez usar funciones
fn main() {
let nombre: String = solicitar_info("cual es tu nombre?");
let pais: String = solicitar_info("de que pais vienes?");
println!("Hola {} como esta el clima en {}?", nombre, pais);
}
fn solicitar_info(pregunta: &str) -> String {
println!("Pregunta: {}", pregunta);
let mut respuesta: String = String::new();
std::io::stdin().read_line(&mut respuesta).unwrap();
return respuesta.trim().to_string()
}
Mi Respuesta:
fn main() {
let mut nombre: String = String::new();
let mut pais: String = String::new();
println!("Por favor introduce tu nombre:");
std::io::stdin().read_line(&mut nombre).unwrap();
nombre = nombre.trim().to_string();
println!("De que pais eres:");
std::io::stdin().read_line(&mut pais).unwrap();
pais = pais.trim().to_string();
println!("Mucho gusto {}, es un bonito pais {}", nombre, pais);
}
Esta seria mi respuesta:
fn main() {
let nombre = read_from_user("Favor de introducir nombre: ");
let ciudad = read_from_user("Favor de ingresar su ciudad: ");
println!("Hola, bienvenido {}, de la ciudad de {}", nombre, ciudad);
}
fn read_from_user(message: &str) -> String {
println!("{}", message);
let mut result = String::new();
std::io::stdin()
.read_line(&mut result)
.unwrap();
return result.trim().to_string();
}
Así lo hice yó
<code>
fn main() {
println!("Bienvenido al aeropuerto imaginario");
println!("De que pais vienes?");
let mut country = String::new();
std::io::stdin().read_line(&mut country).unwrap();
println!("Cual es tu nombre");
let mut name = String::new();
std::io::stdin().read_line(&mut name).unwrap();
println!("Cual estu edad");
let mut age: String = String::new();
std::io::stdin().read_line(&mut age).unwrap();
let age_int: u8 = age.trim().parse().unwrap();
// dias
let mut days: String = String::new();
println!("Cuantos dias estarás aqui?");
std::io::stdin().read_line(&mut days).unwrap();
println!("Hola {}, de {} años, disfruta tu estancia de {} dias en imaginalandia", name, age_int, days);
}
Buenas, dejo mi solución para el reto de esta clase 🤝
fn main() {
let mut name: String = String::new();
let mut country: String = String::new();
println!("Bienvenid@, ¿Cuál es tu nombre?");
std::io::stdin().read_line(&mut name).unwrap();
name = name.trim().to_string();
println!("¿De que pais eres?");
std::io::stdin().read_line(&mut country).unwrap();
country = country.trim().to_string();
println!("Bienvenid@ {} de {}", name, country);
}```
Asi va quedando:
// https://github.com/Ojitos369/curso_rust -> e71cd42
fn temperatura() {
// i8, i16 - enteros con signo
// u8, u16 - enteros sin signo (positivos)
// &str - string
let temperatura_minima: i8 = -3;
let temperatura_maxima: u8 = 32;
let temperatura_promedio: f32 = (temperatura_minima + temperatura_maxima as i8) as f32/ 2.0;
// println!("La termeratura minima en mi ciudad es {} y la maxima es {} y el promedio es {}", temperatura_minima, temperatura_maxima, temperatura_promedio);
println!("La termeratura minima en mi ciudad es {temperatura_minima} y la maxima es {temperatura_maxima} y el promedio es {temperatura_promedio}");
}
fn ingreso_datos() {
// &str -> para strings sencillos, mejor velocidad en procesamiento
// String -> un poco mas complejo, con mas funciones
println!("Ingrese su nombre: ");
let mut nombre: String = String::new();
std::io::stdin().read_line(&mut nombre).unwrap();
// trim() -> Para eliminar espacio en blanco
// to_string() -> Para convertir un &str a un String
nombre = nombre.trim().to_string();
println!("Ingrese su edad: ");
let mut edad: String = String::new();
std::io::stdin().read_line(&mut edad).unwrap();
// trim() -> elimina los espacios en blanco
// parse() -> convierte un string a un tipo de dato
// unwrap() -> manejo de errores
let edad_int: u8 = edad.trim().parse().unwrap();
println!("Hola {nombre} que tiene {edad_int} años");
}
fn main() {
println!("Ingresa la clase: ");
let mut clase: String = String::new();
std::io::stdin().read_line(&mut clase).unwrap();
let clase_int: u8 = clase.trim().parse().unwrap();
match clase_int {
1 => temperatura(),
2 => ingreso_datos(),
_ => println!("Hola clase desconocida"),
}
}
Code
fn main() {
println!("Hola!, bienvenida(o) a nuestro centro informativo.");
println!();
println!("Para brindarle un servicio de calidad, le solicitaremos algunos datos para poder continuar.");
println!();
println!("Cuál es su nombre?");
let mut nombre: String = String::new();
std::io::stdin().read_line(&mut nombre).expect("No se recibió ningún nombre válido");
nombre = nombre.trim().to_string();
println!();
println!("De que ciudad nos visita?");
let mut ciudad: String = String::new();
std::io::stdin().read_line(&mut ciudad).expect("No se recibió ninguna ciudad válida");
ciudad = ciudad.trim().to_string();
println!();
println!();
println!("Excelente! ya tenemos la información completa, y solo para confirmar, le presentamos los datos recabados:");
println!();
println!("Nombre: {}", nombre);
println!("Ciudad: {}", ciudad);
println!();
println!();
println!("Gracias por utilizar nuestros servicios en digitales.");
}
Evidence
Hola!, bienvenida(o) a nuestro centro informativo.
Para brindarle un servicio de calidad, le solicitaremos algunos datos para poder continuar.
Cuál es su nombre?
Charly
De que ciudad nos visita?
Corregidora
Excelente! ya tenemos la información completa, y solo para confirmar, le presentamos los datos recabados:
Nombre: Charly
Ciudad: Corregidora
Gracias por utilizar nuestros servicios en digitales.
Listo!
fn main() {
println!("Por favor, dime tu nombre: ");
let mut name : String = String::new();
std::io::stdin().read_line(&mut name).unwrap();
name = name.trim().to_string();
println!("Por favor, dime ¿de qué país vienes?: ");
let mut pais : String = String::new();
std::io::stdin().read_line(&mut pais).unwrap();
println!("Es un placer conocerte {}, de {} ", name, pais);
}
Yo lo escribí como string literals en lugar de argumentos posicionales y funciona, estuve buscando y encontré respuestas muy variadas, alguien sabe si está bien si lo hago así o voy a hacer el ridículo?
let max_temperature: i8 = 40;
let min_temperature: i8 = -20;
println!("In Chihuahua, Mexico, the highest temperature registered was {max_temperature}°C and the lowest was {min_temperature}°C");
Tambien pueden hacer el trim en el mismo println!();
println!("Hola, bienvenido o bienvenida {} de {} years", nombre.trim(),edad_int);
Lo que el profe define como función por abstracción, en realidad se llaman macros (similar a una función pero diferente) y si es una abstracción de la librería standar, se diferencian de las funciones porque estas pueden aceptar una cantidad variable de argumentos y siempre llevan un bang (!) al final.
Esta es mi solucion agregando algunas cosas más como la edad y el apellido
fn main() {
println!("Porfavor introduce tu nombre: ");
//Obtener nombre
let mut nombre: String = String::new();
std::io::stdin().read_line(&mut nombre).unwrap();
nombre = nombre.trim().to_string();
//Obtener apellido
println!("Porfavor introduce tu apellido: ");
let mut apellido: String = String::new();
std::io::stdin().read_line(&mut apellido).unwrap();
apellido = apellido.trim().to_string();
//Obtener pais
println!("Porfavor introduce tu pais: ");
let mut pais: String = String::new();
std::io::stdin().read_line(&mut pais).unwrap();
pais = pais.trim().to_string();
//Obtener edad
println!("Porfavor introduce tu edad: ");
let mut edad: String = String::new();
std::io::stdin().read_line(&mut edad).unwrap();
//Convertir edad a numero
let edad_int: u8 = edad.trim().parse().unwrap();
println!("Hola, bienvenido/a {} {} de {} años, residente de {}", nombre, apellido, edad_int, pais);
}
Mi solución al reto:
fn main() {
println!("Por favor introduce tu nombre: ");
let mut name : String = String::new();
std::io::stdin().read_line(&mut name).unwrap();
name = name.trim().to_string();
println!("¿De qué país vienes {}?: ", name);
let mut country : String = String::new();
std::io::stdin().read_line(&mut country).unwrap();
country = country.trim().to_string();
println!("Hola {} de {}", name, country);
}
fn main() {
println!("Por favor, introduce tu nombre ");
let mut nombre : String = String::new();
std::io::stdin().read_line(&mut nombre).unwrap();
nombre = nombre.trim().to_string();
// vamos a obtener la edad de la consola
println!("Por favor, introduce tu Pais de origen");
let mut pais : String = String::new();
std::io::stdin().read_line(&mut pais).unwrap();
// Convirtiendo pais a un string sin espacios
pais = pais.trim().to_string();
println!("Hola, bienvenido o bienvenida {} de {}", nombre, pais);
}
Interactuar con datos es una de las especialidades de Rust.
My solution:
fn main() {
println!("What is your name?");
let mut name = String::new();
std::io::stdin().read_line(&mut name).unwrap();
name = name.trim().to_string();
println!("What is your country?");
let mut country = String::new();
std::io::stdin().read_line(&mut country).unwrap();
country = country.trim().to_string();
println!("Hello, {} from {}!", name, country);
}
use std::io::stdin;
fn main()
{
let mut nombre : String = String::new();
println!("Ingrese su nombre: ");
stdin().read_line(&mut nombre).unwrap();
nombre = nombre.trim().to_string();
println!("Hello, {}!", nombre);
let mut nacionalidad : String = String::new();
println!("Ingrese su nacionalidad: ");
stdin().read_line(&mut nacionalidad).unwrap();
nacionalidad = nacionalidad.trim().to_string();
println!(r#"{} es un maravilloso lugar. 🥸 "#, nacionalidad);
}
fn form() {
println!("Hola");
println!("Escribe tu pais");
let mut country = String::new();
std::io::stdin().read_line(&mut country).expect("Input error");
println!("Escribe tu ciudad:");
let mut city = String::new();
std::io::stdin().read_line(&mut city).expect("Input error");
println!("Tu ciudad es {}, y tu pais es {}", city, country);
}
use std::io::{stdin};
fn main() {
let mut str_nombre: String = String::new();
let mut str_edad: String = String::new();
let mut str_pais: String = String::new();
//Limpiar la pantalla
print!("\x1B[2J\x1B[1;1H");
//Mostrar bienvenida y comenzar preguntando el nombre...
println!("\n*********************************************\n¡Hola, bienvenid@ al formulario!\n*********************************************\nPor favor contesta las siguientes preguntas:\n\n¿Cual es tu nombre?");
//Leer nombre de Standard Input...
stdin().read_line(&mut str_nombre).unwrap();
//Remover EOL
str_nombre = str_nombre.trim().to_string();
//Preguntar la edad...
println!("¿Y tu edad?");
//Leer la edad del Standard Input...
stdin().read_line(&mut str_edad).unwrap();
//Remover EOL
str_edad = str_edad.trim().to_string();
//Convertir edad a un entero sin signo
let uint_edad: u8 = str_edad.parse().unwrap();
//Preguntar país...
println!("¿De que país eres?:");
//Leer el país del Standard Input...
stdin().read_line(&mut str_pais).unwrap();
//Remover EOL
str_pais = str_pais.trim().to_string();
//Limpiar la pantalla
print!("\x1B[2J\x1B[1;1H");
//Confirmo registro.
println!("\nHas quedado registrado cómo:\n\n * Nombre: {}\n * Edad: {}\n * País: {}\n\nMuchas gracias por usar el formulario.\n", str_nombre, uint_edad, str_pais);
//fin
}
Resolviendo el problema.
fn main {
let mut nombre: String = String::new();
let mut pais: String = String::new();
nombre = nombre.trim().to_string();
pais = pais.trim().to_string();
println!("Ingrese su nombre: ");
//Leer nombre
std::io::stdin.read_line(&mut nombre).unwrap();
println!("Ingrese el pais de procedencia: ");
//Leer pais
std::io::stdin.read_line(&mut pais).unwrap();
println!("Hola {}, gracias por visitarnos desde {}.",nombre,pais);
}
fn main() {
// Signed numbers
let _x1: i8 = -128; // Occupies 8 bits and its range is -128..=127
let _x2: i16 = 32767; // Occupies 16 bits and its range is -32768..=32767
let _x3: i32 = -2147483648; // Occupies 32 bits and its range is -2147483648..=2147483647
let _x4: i64 = 9223372036854775807; // Occupies 64 bits and its range is -9223372036854775808..=9223372036854775807
let _x5: i128 = -170141183460469231731687303715884105728; // Occupies 128 bits and its range is -170141183460469231731687303715884105728..=170141183460469231731687303715884105727
// Unsigned numbers
let _x6: u8 = 255; // Occupies 8 bits and its range is 0..=255
let _x7: u16 = 65535; // Occupies 16 bits and its range is 0..=65535
let _x8: u32 = 4294967295; // Occupies 32 bits and its range is 0..=4294967295
let _x9: u64 = 18446744073709551615; // Occupies 64 bits and its range is 0..=18446744073709551615
let _x10: u128 = 340282366920938463463374607431768211455; // Occupies 128 bits and its range is 0..=340282366920938463463374607431768211455
// Macro to print to stdout
println!("Print something");
// Strings
// &str offers more speed and String offers more features
let mut _str: &str = "My string"; // Variables are immutable by default, setting mut makes them mutable
println!("The size of '{}' is {}", _str, _str.chars().count()); // The number of characters in the string
let mut n: u8 = 0;
for i in _str.chars(){
println!("Char number {}: {}", n, i);
n += 1;
}
_str = "Changed string";
let mut _str2: String = String::new();
let _str3: String = String::from("String con más funcionalidades");
let _str4: String = "String con más funcionalidades".to_string();
// Fib case
let mut ns: String = String::new();
println!("Enter a number: ");
std::io::stdin().read_line(&mut ns).unwrap();
let n: u8 = ns.trim().parse().unwrap();
if n < 187 {
println!("Fib of {} is {}", n, fib(n));
} else {
println!("You cannot enter numbers greater than 186, because there will be an overflow");
}
}
// Fib linear implementation, only works with n in the range 0..=186
fn fib(n: u8) -> u128 {
return if n > 1 {
let mut i: u8 = 1;
let mut n0: u128 = 0;
let mut n1: u128 = 1;
let mut aux: u128;
while i < n {
aux = n1;
n1 = n1 + n0;
n0 = aux;
i += 1;
}
n1
} else {
n as u128
}
}
fn main() {
println!("Intoduce your name, please: ");
//variable vacía
let mut name: String = String::new();
std::io::stdin().read_line(&mut name).unwrap();
println!("Intoduce your age, please: ");
let mut age: String = String::new();
std::io::stdin().read_line(&mut age).unwrap();
let age_int: u8 = age.trim().parse().unwrap();
//recibir input de usuario
name = name.trim().to_string();
println!("Where you come from? ");
let mut country: String = String::new();
std::io::stdin().read_line(&mut country).unwrap();
country = country.trim().to_string();
println!("Welcome, {name} of {age_int}yo from {country}");
}
fn main() {
println!("Please, write your name: ");
let mut name: String = String::new();
std::io::stdin().read_line(&mut name).unwrap();
println!("Please, write your age: ");
let mut age: String = String::new();
std::io::stdin().read_line(&mut age).unwrap();
println!("Please, write the country where you come from?: ");
let mut country: String = String::new();
std::io::stdin().read_line(&mut country).unwrap();
println!("Please, write your hometown?: ");
let mut hometown: String = String::new();
std::io::stdin().read_line(&mut hometown).unwrap();
name = name.trim().to_string();
let age_int: u8 = age.trim().parse().unwrap();
country = country.trim().to_string();
hometown = hometown.trim().to_string();
println!("Hi, Welcome {}.", name);
println!("Your age is {} years, right. Thanks!", age_int);
println!("You come from {} in {}, That's nice.", hometown, country);
}
fn main() {
let mut name = String::new();
let mut city = String::new();
println!("Please type your name: ");
std::io::stdin().read_line(&mut name).unwrap();
println!("Please type your city: ");
std::io::stdin().read_line(&mut city).unwrap();
println!("Welcome {}, your city is {}.", name.trim(), city.trim());
}
fn main() {
let name: &str = "Rust";
let year = 1.63;
println!("Hello, you are using {} version {}",name,year);
println!("Por favor introduce tu nombre: ");
let mut user = String::new();
std::io::stdin().read_line(&mut user).unwrap();
user = user.trim().to_string();
println!("Welcome {} this is rust 🦀 ", user);
//Obtener la edad y convertirla en un numero:
println!("Please, How old you? ");
let mut age = String::new();
std::io::stdin().read_line(&mut age).unwrap();
//convierte a numero
let age_int: u8 = age.trim().parse().unwrap();
println!("Excellent {} you are {} year old..!",user, age_int);
}
fn main() {
println!("Escribe tu nombre: ");
let mut nombre : String = String::new();
std::io::stdin().read_line(&mut nombre).unwrap();
nombre = nombre.trim().to_string();
//obtener el país de origen
println!("país de origen: ");
let mut pais : String = String::new();
std::io::stdin().read_line(&mut pais).unwrap();
pais = pais.trim().to_string();
println!("Hola como estas? tu eres {} y vienes de {}", nombre, pais);
}
dejo resuelto el RETO 2 en github
https://github.com/jeigar2/curso-rust/tree/RecibiendoDatosUsuario
código
fn main() {
// mensaje a mostar en pantalla
println!("Ingrese su nombre:");
// debe ser mutable para recibir el nombre
let mut nombre: String = String::new();
// unwrap se utiliza para tratar los errores
std::io::stdin().read_line(&mut nombre).unwrap();
// formatea el texto para eliminar saltos de línea y espacios en blanco.
nombre = nombre.trim().to_string();
println!("Que Dios te bendiga {}", nombre);
// mensaje a mostar en pantalla
println!("Ingrese su edad:");
// debe ser mutable para recibir el texto con la edad
let mut edad: String = String::new();
std::io::stdin().read_line(&mut edad).unwrap();
// formatea el texto para eliminar saltos de línea y espacios en blanco
// y transforma a entero
let int_edad: u8 = edad.trim().parse().unwrap();
// mensaje a mostar en pantalla
println!("En que país nació:");
// debe ser mutable para recibir el pais
let mut pais: String = String::new();
// unwrap se utiliza para tratar los errores
std::io::stdin().read_line(&mut pais).unwrap();
// formatea el texto para eliminar saltos de línea y espacios en blanco.
pais = pais.trim().to_string();
println!("Que Dios te bendiga {} y también a tu país {}", nombre, pais);
// {} es un placeholder
// cada uno de ello se reemplaza por el valor de las varibles recibidas
// en el resto de argumentos de la función (nombre, int_edad)
println!("{} tienes {} años", nombre, int_edad);
}
Salida
Ingrese su nombre:
_Alicia_
Que Dios te bendiga _Alicia_
Ingrese su edad:
_34_
En que país nació:
_Australia_
Que Dios te bendiga _Alicia_ y también a tu país _Australia_
_Alicia_ tienes _34_ años
fn main() {
let nombre: &str = "Camilo";
let edad: u8 = 36;
let ciudad: &str = "Bogotá";
let temp_max: u8 = 26;
let temp_min: i8 = -2;
println!("Hola mi nombre es {} y tengo {} años, vivo en {} que tiene una temperatura máxima de {} grados y en la madrugada una temperatura mínima de {} grados", nombre, edad, ciudad, temp_max, temp_min);
}
Aquí mi código de solución:
fn main(){
let nombre: String = pedir_dato("nombre".to_string());
let pais: String = pedir_dato("pais".to_string());
println!("Hola {} de {}", nombre, pais);
}
fn pedir_dato(dato: String) -> String{
let stdin = std::io::stdin();
let mut dato_ingresado = String::new();
loop{
println!("Ingresa tu {}: ", dato);
stdin.read_line(&mut dato_ingresado).unwrap();
dato_ingresado = dato_ingresado.trim().to_string();
if dato_ingresado.len() > 0
{
break;
}
}
return dato_ingresado;
}
Implementación con una función para realizar las preguntas y limpiar la cadena.
fn ask_info(question: &str) -> String {
println!("{}", question);
let mut answer: String = String::new();
std::io::stdin().read_line(&mut answer).unwrap();
return answer.trim().to_string();
}
fn main() {
let name: String = ask_info("What's your name?");
let age: u8 = ask_info("How old are you?").parse().unwrap();
println!(
"Hola, soy {name} y tengo {age} años",
name = name,
age = age
);
}
Linda la sintaxis de Rust. Si uno tiene experiencia en C++ o Java, no causa tanto susto esos comandos tan extensos y raros.
fn preguntar_nombre_y_pais() {
println!("Por favor introduce tu nombre: ");
let mut nombre: String = String::new();
std::io::stdin().read_line(&mut nombre).unwrap();
println!("Por favor introduce tu nombre: ");
let mut pais: String = String::new();
std::io::stdin().read_line(&mut pais).unwrap();
println!(“Hola, {} eres de {}”, nombre.trim(), pais.trim());
}
fn main() {
let name_nightclub:String = "Coco Bongo".to_string();
println!("");
println!("{}",name_nightclub);
println!("----------");
println!("");
println!("Please enter your name...");
let mut name: String = String::new();
std::io::stdin().read_line(&mut name).unwrap();
name = name.trim().to_string();
println!("What country are you from {}?", name);
let mut country: String = String::new();
std::io::stdin().read_line(&mut country).unwrap();
country = country.trim().to_string();
println!("Please enter your age...");
let mut age: String = String::new();
std::io::stdin().read_line(&mut age).unwrap();
let age_int:u8=age.trim().parse().unwrap();
println!("");
println!("Hello {} from {}, you are {} years old.",name,country,age_int);
println!("");
println!(" Welcome to {}", name_nightclub);
}
Aqui cumpliendo el reto
fn main() {
println!("Please! Enter your name: ");
let mut name : String = String::new();
std::io::stdin().read_line(&mut name).unwrap();
name = name.trim().to_string();
println!("Please! Enter your age: ");
let mut age : String = String::new();
std::io::stdin().read_line(&mut age).unwrap();
let age_int : u8 = age.trim().parse().unwrap();
println!("Please! Enter your country of origin: ");
let mut country : String = String::new();
std::io::stdin().read_line(&mut country).unwrap();
country = country.trim().to_string();
println!("Hello Welcome {} you age is {} years old and your country origin is {}", name, age_int, country);
}
Mi aporte al reto
fn main() {
let mut name: String = String::new();
println!("Hello, please tell me your name:");
std::io::stdin().read_line(&mut name).unwrap();
name = name.trim().to_string();
println!("Welcome {}!", name);
println!("How old are you?");
let mut input_age: String = String::new();
std::io::stdin().read_line(&mut input_age).unwrap();
println!("Where are you from?");
let mut origin: String = String::new();
std::io::stdin().read_line(&mut origin).unwrap();
origin = origin.trim().to_string();
let years_in_future: u8 = 31;
let age_in_future: u8 = input_age.trim().parse::<u8>().unwrap() + years_in_future;
println!(
"Nice to meet you {} from {}, you will be {} years old in {} years.",
name, origin, age_in_future, years_in_future
);
}
Aquí dejo mi solución al ejercicio propuesto por el profesor:
fn main() {
let name: String = ask_user_for("Por favor ingresa tu nombre: ");
let city: String = ask_user_for("Por favor ingresa tu ciudad: ");
println!("Hola, {}. Gracias por usar el script desde {}.", name, city);
}
fn ask_user_for(label: &str) -> String {
let mut user_answer: String = String::new();
println!("{}", label);
std::io::stdin().read_line(&mut user_answer).unwrap();
user_answer.trim().to_string()
}
Leyendo un poco más sobre variables en Rust, me di cuenta que se soporta shadowing.
Shadowing nos permite declarar una nueva variable, incluso con un tipo diferente, que tenga el mismo nombre de otra variable declarada anteriormente en el bloque de código o en un bloque superior.
Esto nos permite que en lugar de hacer:
// Obtener la edad del usuario
println!("Por favor introduce tu edad: ");
let mut age: String = String::new();
std::io::stdin().read_line(&mut age).unwrap();
// Convertir la edad a un número
let age_int: u8 = age.trim().parse().unwrap();
Podamos hacer:
// Obtener la edad del usuario
println!("Por favor introduce tu edad: ");
let mut age: String = String::new();
std::io::stdin().read_line(&mut age).unwrap();
// Convertir la edad a un número
let age: u8 = age.trim().parse().unwrap();
Sin necesidad de tener mantener el valor del age como String a futuro en nuestro código.
Esto puede ser útil para mejorar la legibilidad, en lugares donde no sea necesario seguir haciendo uso de la variable original sino de la parseada.
fn main() {
//crear las variables
let mut nombre=String::new();
let mut ciudad=String::new();
//Se gurdan las variables que el usuario Introduzca.
println!("Digita tu nombre: ");
std::io::stdin().read_line(&mut nombre).expect("Solo letras");
nombre=nombre.trim().to_string();//Evita saltos de Linea.
println!("Digita tu ciudad: ");
std::io::stdin().read_line(&mut ciudad).expect("Solo letras");
ciudad=ciudad.trim().to_string();//evita saltos de Linea
//Se imprime el resultado Final
println!("Su nombre es {nombre}, y vive en {ciudad}");
}
Reto
fn main(){
form_foraneo()
}
fn form_foraneo(){
println!("Happy coding, ingresa por favor tu nombre: ");
let mut nombre: String = String::new();
std::io::stdin().read_line(&mut nombre).unwrap();
nombre = nombre.trim().to_string();
println!("Happy coding, ingresa por favor tu pais de origen: ");
let mut pais: String = String::new();
std::io::stdin().read_line(&mut pais).unwrap();
pais = pais.trim().to_string();
print!("Hola, bienvenido {} tu pais de origen es {} ", nombre,pais);
}
fn main() {
let min_temp: i8 = -21;
let max_temp: i8 = 38;
let mut input_name: String = String::new();
let mut input_age: String = String::new();
println!("Por favor introduzca su nombre:");
std::io::stdin().read_line(&mut input_name).unwrap();
println!("Por favor introduzca su edad:");
std::io::stdin().read_line(&mut input_age).unwrap();
let name: &str = input_name.trim();
let age: u8 = input_age.trim().parse().unwrap();
say_hello(name, age);
print_temp(min_temp, max_temp);
}
fn say_hello(name: &str, age: u8) {
return println!("Bienvenido {}, tienes {} anios", name, age)
}
fn print_temp(min_temp: i8, max_temp: i8) {
return println!("La temperatura maxima en Deggendorf fue de {} y la mas alta fue de {}", min_temp, max_temp)
}
Want to see more contributions, questions and answers from the community?