Last active
March 9, 2025 01:02
-
-
Save HiroNakamura/c48f38a04e17fde5a550f44c695022cc to your computer and use it in GitHub Desktop.
Course: Rust Programming Crash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::env; | |
use std::io; | |
use std::fs::File; | |
mod modulo; | |
// Estructura tradicional | |
struct Color { | |
red: u8, | |
blue: u8, | |
green: u8, | |
} | |
// Estructura con funciones | |
struct Educacion { | |
nombre_escuela: String, | |
titulo_mayor: String, | |
titulo_menor: String, | |
} | |
impl Color { | |
fn nuevo(red: u8, blue: u8, green: u8) -> Color { | |
Color { | |
red: red, | |
blue: blue, | |
green: green, | |
} | |
} | |
} | |
struct Rectangulo { | |
alto: u32, | |
ancho: u32, | |
} | |
impl Rectangulo { | |
fn get_area(&self) -> u32 { | |
self.ancho * self.alto | |
} | |
} | |
struct Cuadrado { | |
lado: u32, | |
} | |
// Estructura tipo tupla | |
struct ModeloColor(u8, u8, u8); | |
// Enumeraciones | |
enum IpAddressKind { | |
V4(u8, u8, u8, u8), | |
V6(String), | |
} | |
struct IpAddress { | |
kind: IpAddressKind, | |
address: String, | |
} | |
enum Cafe { | |
C(String), | |
M(String), | |
G(String), | |
} | |
enum Option<T> { | |
None, | |
Some(T), | |
} | |
enum Message { | |
Write(String), | |
Color(i32, i32, i32), | |
Move(i32, i32), | |
Quit, | |
} | |
impl Message { | |
fn call(&self) { | |
println!("Esto es una llamada dentro de la implementación."); | |
} | |
} | |
fn main() { | |
println!("{welcome}", welcome = "¡Hola, mundo en Rust!"); | |
test_a(); | |
test_b(); | |
test_c(); | |
test_d(); | |
test_e(); | |
test_f(); | |
test_g(); | |
test_h(); | |
test_i(); | |
test_j(); | |
test_k(); | |
test_l(); | |
test_m(); | |
test_n(); | |
test_o(); | |
test_p(); | |
test_q(); | |
let args: Vec<String> = env::args().collect(); | |
println!("{:?}", args); | |
println!("{:?}", args[0]); | |
if args.len() >= 1 { | |
println!("{:?}", args[1]); | |
for x in args.iter() { | |
println!("{} ", x); | |
} | |
} | |
} | |
fn test_q(){ | |
let file = File::open("noexiste.txt"); | |
let foo = match file{ | |
Ok(archivo) => archivo, | |
Err(error) =>{ | |
panic!("El archivo no existe!"); | |
} | |
}; | |
let otro_file = File::open("noexiste.txt").expect("El archivo aun no existe!"); | |
} | |
fn test_p() { | |
let nombre = String::from("Hola, mundo!"); | |
println!( | |
"{} posición 9 de la cadena es: {}", | |
nombre, | |
match nombre.chars().nth(9) { | |
Some(valor) => valor.to_string(), | |
None => "Ningun caracter en la posición 9".to_string(), | |
} | |
); | |
} | |
fn test_o() { | |
let my_message: Message = Message::Write(String::from("Este es un mensaje")); | |
my_message.call(); | |
} | |
fn test_n() { | |
let cuadrado: Cuadrado = Cuadrado { lado: 33 }; | |
let area = get_area(&cuadrado); | |
println!("Lado = {}", cuadrado.lado); | |
println!("Area = {}", area); | |
let anchura = 43 as u32; | |
let altura: u32 = 30; | |
let rectangulo: Rectangulo = Rectangulo { | |
ancho: anchura, | |
alto: altura, | |
}; | |
println!( | |
"Rectangulo ancho: {}, alto: {} ", | |
rectangulo.ancho, rectangulo.alto | |
); | |
println!("Area del rectangulo: {}", rectangulo.get_area()); | |
} | |
fn get_area(cuadrado: &Cuadrado) -> u32 { | |
cuadrado.lado * cuadrado.lado | |
} | |
fn test_m() { | |
let libro = String::from("El libro de los augurios."); | |
mostrar(&libro); | |
let cadena: String = String::from("Doroteo Arango"); | |
let sub_cadena = &cadena[0..7]; | |
println!("{}", sub_cadena); // Doroteo | |
println!("{}", &cadena[8..14]); // Arango | |
} | |
fn mostrar(titulo: &str) { | |
println!("Titulo: {}", titulo); | |
} | |
fn test_l() { | |
let mut a = 15 as u32; | |
let mut b: u32 = 40; | |
println!("MCD de {} y {} es:", a, b); | |
while b != 0 { | |
let temp = b; | |
println!("temp: {}", temp); | |
b = a % b; | |
println!("b: {}", b); | |
a = temp; | |
println!("a:{}", a); | |
} | |
println!("{}", a); | |
} | |
fn test_k() { | |
modulo::maths(); | |
let a: u32 = 21; | |
let b: u32 = 36; | |
println!("Suma de {} + {} es {} ", a, b, modulo::add(a, b)); | |
} | |
fn test_j() { | |
let ip_v4 = IpAddressKind::V4(0, 0, 0, 0); | |
let ip_v6 = IpAddressKind::V6(String::from("2001:0db8:85a3:0000:0000:8a2e:0370:7334")); | |
// Función para mostrar la dirección IP | |
fn mostrar_ip(ip: &IpAddressKind) { | |
match ip { | |
IpAddressKind::V4(a, b, c, d) => { | |
println!("IPv4: {}.{}.{}.{}", a, b, c, d); | |
} | |
IpAddressKind::V6(addr) => { | |
println!("IPv6: {}", addr); | |
} | |
} | |
} | |
// Mostramos ambas direcciones | |
println!("Mostrando direcciones IP:"); | |
mostrar_ip(&ip_v4); | |
mostrar_ip(&ip_v6); | |
// Ejemplo de verificación simple | |
match ip_v4 { | |
IpAddressKind::V4(a, _, _, _) if a == 192 => { | |
println!("Esta es una dirección de red privada"); | |
} | |
_ => println!("No es una dirección de red privada"), | |
} | |
// Creamos algunos ejemplos de cafés | |
let cafe_chico = Cafe::C(String::from("Expresso")); | |
let cafe_mediano = Cafe::M(String::from("Latte")); | |
let cafe_grande = Cafe::G(String::from("Capuchino")); | |
// Función para mostrar y calcular precio del café | |
fn procesar_cafe(cafe: &Cafe) { | |
match cafe { | |
Cafe::C(tipo) => { | |
println!("Café Chico - {}: $2.50", tipo); | |
} | |
Cafe::M(tipo) => { | |
println!("Café Mediano - {}: $3.00", tipo); | |
} | |
Cafe::G(tipo) => { | |
println!("Café Grande - {}: $3.50", tipo); | |
} | |
} | |
} | |
// Procesamos cada café | |
println!("Pedidos de café:"); | |
procesar_cafe(&cafe_chico); | |
procesar_cafe(&cafe_mediano); | |
procesar_cafe(&cafe_grande); | |
// Ejemplo de verificación adicional | |
match &cafe_grande { | |
Cafe::G(tipo) if tipo == "Capuchino" => { | |
println!("¡El capuchino grande es nuestra especialidad!"); | |
} | |
_ => println!("Buen elección de café"), | |
} | |
} | |
impl Educacion { | |
// Constructor & funcion asociativa | |
fn constructing_eduacion(nombre_esc: &str, titulo_may: &str, titulo_men: &str) -> Educacion { | |
Educacion { | |
nombre_escuela: nombre_esc.to_string(), | |
titulo_mayor: titulo_may.to_string(), | |
titulo_menor: titulo_men.to_string(), | |
} | |
} | |
// Metodos | |
fn educacion_total(&self) -> String { | |
format!( | |
"{}, {}, {}", | |
self.nombre_escuela, self.titulo_mayor, self.titulo_menor | |
) | |
} | |
} | |
fn test_i() { | |
let mut my_color = Color { | |
red: 0, | |
blue: 200, | |
green: 255, | |
}; | |
my_color.blue = 255; | |
my_color.green = 0; | |
my_color.red = 200; | |
println!( | |
"Color {} {} {}", | |
my_color.red, my_color.blue, my_color.green | |
); | |
let other_color = ModeloColor(225 as u8, 123, 127 as u8); | |
println!( | |
"ModeloColor {} {} {}", | |
other_color.0, other_color.1, other_color.2 | |
); | |
let mut my_educacion1 = Educacion::constructing_eduacion( | |
"CUTVAC", | |
"Titulo en Ingenieria en computacion", | |
"Ningun otro", | |
); | |
println!( | |
"Educacion-- Escuela: {} , Titulo mayor: {} , Titulo menor: {}", | |
my_educacion1.nombre_escuela, my_educacion1.titulo_mayor, my_educacion1.titulo_menor | |
); | |
println!("Educacion total: {}", my_educacion1.educacion_total()); | |
let red: u8 = 250; | |
let blue = 234 as u8; | |
let green = 0; | |
let my_other_color: Color = Color::nuevo(red, blue, green); | |
println!( | |
"Color ({} - {} - {})", | |
my_other_color.red, my_other_color.blue, my_other_color.green | |
); | |
} | |
fn test_h() { | |
let vector1 = vec![1, 2, 3, 4]; | |
let vector2 = &vector1; | |
println!("Vector: {:?}", (&vector1, vector2)); | |
} | |
fn test_g() { | |
let mut input = String::new(); | |
println!("Introduce algun texto: "); | |
io::stdin() | |
.read_line(&mut input) | |
.expect("Failed to read line"); | |
println!("Texto introducido: {}", input); | |
} | |
fn test_f() { | |
let mut counter = 0 as i32; | |
loop { | |
println!("Contador {}", counter); | |
counter += 1; | |
if counter == 4 { | |
break; | |
} | |
} | |
counter = 0; | |
while counter <= 100 { | |
if counter % 15 == 0 { | |
println!("Fizzbuzz {}", counter); | |
} else if counter % 3 == 0 { | |
println!("Fizz {}", counter); | |
} else if counter % 5 == 0 { | |
println!("Buzz {}", counter); | |
} else { | |
println!("Counter {}", counter); | |
} | |
counter += 1; | |
} | |
for i in 2..6 { | |
println!("No. {}", i); | |
} | |
let vector = [22, 33, 44, 55]; | |
for vect in vector.iter() { | |
println!("valor {}", vect); | |
} | |
} | |
fn test_e() { | |
if true { | |
println!("{message}", message = "Es verdadero."); | |
} | |
if !true { | |
println!("{message}", message = "No es es verdadero."); | |
} else { | |
println!("{message}", message = "Esto si es verdadero."); | |
} | |
let booleano = 23 > 22; | |
if booleano && false { | |
println!("{warning}", warning = "Esto es un error."); | |
} else if !booleano || !true { | |
println!("{warning}", warning = "Esto es un error."); | |
} else { | |
println!("{success}", success = "Esto es correcto."); | |
} | |
} | |
fn test_d() { | |
let flag: bool = 34 > 0; | |
println!("flag es {}", flag); | |
let mut condition = flag && 3 as f32 > 2.0; | |
println!("condition es {}", condition); | |
condition = flag && false; | |
println!("condition es {}", condition); | |
condition = !flag && false; | |
println!("condition es {}", condition); | |
condition = flag && !false; | |
println!("condition es {}", condition); | |
condition = 2 as i32 != 0 || false; | |
println!("condition es {}", condition); | |
} | |
fn test_c() { | |
let suma_numeros = |x: i32, y: i32| x + y; | |
let m = 34; | |
let n = 21 as i32; | |
println!( | |
"Suma con clousure de {} + {} es {} ", | |
m, | |
n, | |
suma_numeros(m, n) | |
); | |
// Podemos usar variables externas | |
let z = 32 as i32; | |
let suma_numeros = |x: i32, y: i32| x + y + z; | |
println!( | |
"Suma con clousure de {} + {} + {} es {} ", | |
m, | |
n, | |
z, | |
suma_numeros(m, n) | |
); | |
// Definimos una variable que el closure va a capturar | |
let calcular_factorial = |n: u32| -> u32 { | |
let mut resultado = 1; | |
for i in 1..=n { | |
resultado *= i; | |
} | |
resultado | |
}; | |
// Probamos el closure con algunos valores | |
let numero = 5; | |
println!( | |
"El factorial de {} es {}", | |
numero, | |
calcular_factorial(numero) | |
); | |
println!("El factorial de 3 es {}", calcular_factorial(3)); | |
println!("El factorial de 0 es {}", calcular_factorial(0)); | |
} | |
fn test_b() { | |
println!("{:?}", (false, 34, "ABCDE")); | |
println!("{:b}", 7); // 111 | |
println!("{:b}", 6); // 110 | |
println!("{:b}", 5); // 101 | |
println!("Maximo de i32 es {}", std::i32::MAX); | |
println!("Maximo de i64 es {}", std::i64::MAX); | |
println!("Maximo de f32 es {}", std::f32::MAX); | |
println!("Maximo de f64 es {}", std::f64::MAX); | |
let x = 21 as i32; | |
let y: i32 = 32; | |
println!("Suma de {} + {} es {} ", x, y, add(x, y)); | |
println!("Resta de {} + {} es {} ", x, y, sub(x, y)); | |
} | |
fn test_a() { | |
let a = 21; | |
let b = 32.43; | |
let mut c = a as f64 + b; | |
c = c * 2.0; | |
println!("c = {}", c); | |
} | |
fn add(n1: i32, n2: i32) -> i32 { | |
n1 + n2 | |
} | |
fn sub(n1: i32, n2: i32) -> i32 { | |
n1 - n2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment