Skip to content
Exercise · Your First Program · lesson 6 of 7

Exercise: greeting

Write a function fn greeting(name: &str) -> String that returns a greeting: the word Hello, a comma, a space, the name name and an exclamation mark.

The function is already in the stub. Keep its first line as it is: name: &str is the name the function receives, and -> String is the string it returns. The body holds the format! macro: it understands the same {} and {name} as println!, but instead of printing the string it returns it. There is no semicolon after format!(…), so its string becomes the function's result.

  • greeting("Rust") → "Hello, Rust!"
  • greeting("Мир") → "Hello, Мир!"
  • greeting("") → "Hello, !"

Constraints: name is any string, including an empty one, several words or Cyrillic; the function inserts it as it is.

The checks are on the greeting_test.rs tab: you can read them but not change them. A failed check prints the line ✗ greeting("Rust") == "Hello, Rust!" got: "": on the left are the call and the expected answer, and after got: is what your function returned. If the program does not compile, no check runs, and the compiler's message appears instead.

Do not add extra use lines unless the task says so explicitly.

greeting.rs — rust
rust · 4 lines
Ctrl+Enter run · Esc leave editor