Last active
October 22, 2024 12:24
-
-
Save Rahiche/a61a2bdf6a722e67958bd794e92bd57e to your computer and use it in GitHub Desktop.
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::io; | |
use rand::Rng; | |
// A simple struct to represent a person | |
struct Person { | |
name: String, | |
age: u32, | |
} | |
impl Person { | |
fn new(name: String, age: u32) -> Person { | |
Person { name, age } | |
} | |
fn greet(&self) { | |
println!("Hello, my name is {} and I am {} years old!", self.name, self.age); | |
} | |
} | |
// Function to generate a random number and return it with a message | |
fn generate_lucky_number() -> u32 { | |
let lucky_number = rand::thread_rng().gen_range(1..=100); | |
println!("Your lucky number for today is: {}", lucky_number); | |
lucky_number | |
} | |
fn main() { | |
println!("Welcome to the enhanced Rust program!"); | |
// Get user input | |
println!("Please enter your name:"); | |
let mut input = String::new(); | |
io::stdin() | |
.read_line(&mut input) | |
.expect("Failed to read line"); | |
let name = input.trim().to_string(); | |
// Create a new Person instance | |
let person = Person::new(name, 25); | |
person.greet(); | |
// Generate and use lucky number | |
let lucky_num = generate_lucky_number(); | |
if lucky_num > 50 { | |
println!("That's a high number - you're having a lucky day!"); | |
} else { | |
println!("That's a lower number - but don't worry, luck is what you make of it!"); | |
} | |
// Demonstrate vector operations | |
let mut numbers = vec![1, 2, 3, 4, 5]; | |
numbers.push(6); | |
let sum: i32 = numbers.iter().sum(); | |
println!("The sum of numbers 1 through 6 is: {}", sum); | |
println!("Thank you for running this program!"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment