Last active
May 10, 2025 22:25
-
-
Save mjgargani/f65a41b9ee2ab5c8f838fa0dabc3b6ed to your computer and use it in GitHub Desktop.
Simple Calculator in Rust
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
| // Trying to learn Rust - Simple Calculator | |
| // Tentando aprender Rust - Calculadora Simples | |
| // Define possible operations as an enum (enumeration) | |
| // Define possíveis operações com tipo enum (enumeração) | |
| enum Operation { | |
| Add, // Soma | |
| Subtract, // Subtração | |
| Multiply, // Multiplicação | |
| Divide, // Divisão | |
| } | |
| // Function that takes an operation ("op") and a reference to a list of numbers. | |
| // Uses "match" (like switch in JS) to select the behavior. | |
| // Função que recebe uma operação ("op") e uma referência para uma lista de números. | |
| // Usa "match" (semelhante ao switch do JS) para selecionar o comportamento. | |
| fn calculate(op: Operation, numbers: &Vec<f64>) -> f64 { | |
| match op { | |
| Operation::Add => numbers.iter().sum(), // Sum all numbers | Soma todos os números | |
| Operation::Subtract => numbers.iter().map(|x| -x).sum(), | |
| // Subtract by inverting the sign | Subtrai invertendo o sinal | |
| Operation::Multiply => numbers.iter().fold(1.0, |acc, x| acc * x), | |
| // Start with 1.0 and multiply all elements (like JS .reduce()) | |
| // Começa com 1.0 e multiplica todos os elementos (como o .reduce() do JS) | |
| Operation::Divide => { | |
| // Make sure there are at least two numbers | |
| // Garante que há pelo menos dois números | |
| if numbers.len() < 2 { | |
| return f64::NAN; // Not-a-Number (invalid operation) | |
| // Operação inválida | |
| } | |
| // Divide the first number by the rest | |
| // Divide o primeiro número pelo restante | |
| numbers.iter().skip(1).fold(numbers[0], |acc, x| acc / x) | |
| } | |
| } | |
| } | |
| fn main() { | |
| let values = vec![2.2, 3.0, 4.4, 5.0]; // f64 (64-bit float) | |
| println!("Values: {:?}", values); | |
| // Use debug print for the original list | Usa debug print para a lista original | |
| // Execute each operation using the calculate function | |
| // Executa cada operação usando a função calculate | |
| println!("Add: {:.2}", calculate(Operation::Add, &values)); | |
| println!("Subtract: {:.2}", calculate(Operation::Subtract, &values)); | |
| println!("Multiply: {:.2}", calculate(Operation::Multiply, &values)); | |
| println!("Divide: {:.2}", calculate(Operation::Divide, &values)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment