Exercise: Hello World
hello-world
Welcome to your first Rust exercise! You'll write a simple function that creates a personalized greeting.
This exercise teaches you:
- How to define a function in Rust
- How to use the
format!macro for string interpolation - How to work with string slices (
&str)
๐ฏ Learning Objectives
Thinking
Doing
๐ฌ Discussion
- How do you create formatted strings in other programming languages?
- Why might Rust use a macro (`format!`) instead of a method?
- What's the difference between printing a string and returning one?
๐ก 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?
- It takes a format string with placeholders (
{}) - Each
{}is replaced with the corresponding argument - It returns a new
String(owned data on the heap)
Why does the function return String but take &str?
&stris a borrowed reference to string data - we just need to read the nameStringis 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
- **String types**: What would happen if the function returned `&str` instead
- **Ownership**: The `format!` macro creates a new `String`. Who owns that
- **Alternatives**: Can you think of other ways to solve this problem?
- **Edge cases**: The test includes an empty string. Are there other edge
- **Extension**: How would you modify this function to support different