Hello, World!

Challenge

Ask the user for their name and greet them.

Solution

This is a variation of the classic "Hello, World" program. Instead of just printing out a fixed string, we need to read a string use it in our greeting:

What is your name?
Huynh
Hello, Huynh!
use std::io;

fn main() -> io::Result<()>{
    println!("What is your name?");

    let mut name = String::new();
    io::stdin().read_line(&mut name)?;
    let name = name.trim();

    println!("Hello, {name}!");

    Ok(())
}

An interesting Rust feature used here is variable shadowing, where the second variable name shadows the first variable of the same name. Also, note that the compiler guarantees that the second variable is not a dangling reference.

Variation 1

In this variation, no variable is allowed. Therefore, we cannot no longer use Stdin::read_line(), which writes to an existing buffer. Instead, we can use Stdin::lines(), which returns an iterator over input lines.

    println!(
        "Hello, {}!",
        io::stdin() // Get a handle to stdin
            .lines() // iterate over input lines
            .next() // get the first one
            .expect("No line entered")? // unwrap it
            .trim() // trim whitespaces
    );

Doing multiple things in one statement like this maybe a bad practice, but we did solve the challenge.

Variation 2

Now, we want different greetings for different people. The first thing we need to add is a list of greetings to choose from. Here is a short list:1

const GREETINGS: &[&str] = &[
    "Hi",
    "Hi there",
    "Hey",
    "Hello",
    "Hello, nice to meet you",
    "I've heard so much about you",
];

As there are no further requirements, we can choose among several equally acceptable approaches, for example:

  • Choose a random greeting every time.
  • Choose the greeting based on the initials.
  • Choose the greeting based on a hash of the name.

Let's go with the first approach. To make this easier, we shall depend on the rand crate to generate random numbers:

# File: Cargo.toml
[dependencies]
rand = "0.8.5"
// File: hello_v2.rs
use rand::{seq::SliceRandom, thread_rng};

And here is the code to print randomized greetings:

    let mut rng = thread_rng();
    println!("{}, {}!", GREETINGS.choose(&mut rng).unwrap(), name);
1

As a non-native English speaker, I'm always amazed by the variety of ways to say "Hello" in English. For example, this blog documents "107 interesting and different ways to say hi in English".