Hello, Rustacean!
Easy
+2 pts
Intro to Rust
1/15
🎯 In Python, returning a string from a function is straightforward:
def motto() -> str:
return "Fearless concurrency"
Rust works similarly, but with a few differences you'll see right away:
fn motto() -> String {
"Fearless concurrency".to_string()
}
The fn keyword replaces def. The return type goes after -> (just like Python type hints, but required in Rust). And the last expression without a semicolon is automatically returned — no return keyword needed.
String vs &str — a first look
You'll notice the return type is String, not str. Rust has two main string types:
&str— a string slice (borrowed, like a read-only view)String— an owned string (heap-allocated, like Python'sstr)
For now, just know that "Hello" is a &str literal, and .to_string() or .into() converts it to an owned String. We'll explore this distinction in depth later.
Your Task
Implement the greet function to return "Hello, Rustacean!" as an owned String.
Example
assert_eq!(greet(), "Hello, Rustacean!");
Further Reading
- The Rust Book — Functions — defining functions and return values
- The Rust Book — The String Type — String vs &str introduction
fn greet() -> String {
// your code here
todo!()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_greet() {
assert_eq!(greet(), "Hello, Rustacean!");
}
}