โ† Back to Examples

Exercise: Hello World

hello-world
โญ beginner โฑ๏ธ 10 min

Welcome to your first Rust exercise! You'll write a simple function that creates a personalized greeting.

This exercise teaches you:

๐ŸŽฏ Learning Objectives

Thinking

Doing

๐Ÿ’ฌ Discussion

src/lib.rs

๐Ÿ’ก Hints

Hint 1: String Formatting in Rust

Rust uses the format! macro to create formatted strings. It works similarly to println!, but instead of printing to the console, it returns a String.

let s = format!("Hello, {}!", "World");
// s is now "Hello, World!"

The {} is a placeholder that gets replaced with the argument.

Hint 2: Using the name Parameter

You need to use the name parameter inside the format! macro:

format!("some text with {}", name)

Remember, you need to include "Hello, " at the start and "!" at the end.

Hint 3: The Complete Solution

Here's the full implementation:

pub fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}

That's it! The format! macro handles creating the String for you.

โš ๏ธ Try the exercise first! Show Solution
/// Returns a personalized greeting.
///
/// # Arguments
///
/// * `name` - The name to include in the greeting
///
/// # Examples
///
/// ```
/// let greeting = greet("World");
/// assert_eq!(greeting, "Hello, World!");
/// ```
pub fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}

Explanation

The solution uses the format! macro, which is part of Rust's standard library.

Why format! instead of string concatenation?

In some languages, you might write:

But Rust's + operator for strings has specific ownership requirements. The format! macro is more flexible and idiomatic for creating formatted strings.

How does format! work?

  1. It takes a format string with placeholders ({})
  2. Each {} is replaced with the corresponding argument
  3. It returns a new String (owned data on the heap)

Why does the function return String but take &str?

  • &str is a borrowed reference to string data - we just need to read the name
  • String is an owned, growable string - we're creating new data
  • This pattern (borrow input, return owned) is very common in Rust

You could also write it as:

But format! is cleaner and more readable for this use case.

๐Ÿงช Tests

View Test Code
// Note: The greet function should be defined above

#[test]
fn test_greet_world() {
    assert_eq!(greet("World"), "Hello, World!");
}

#[test]
fn test_greet_name() {
    assert_eq!(greet("Alice"), "Hello, Alice!");
}

#[test]
fn test_greet_with_spaces() {
    assert_eq!(greet("John Doe"), "Hello, John Doe!");
}

#[test]
fn test_greet_empty() {
    // Edge case: what happens with an empty name?
    assert_eq!(greet(""), "Hello, !");
}

๐Ÿค” Reflection