Slices as Function Parameters
Part of the Logic & Flow section of Coddy's Rust journey — lesson 56 of 66.
When writing functions that work with strings, using &str as a parameter type instead of String makes your functions much more flexible and useful.
A function that takes a String parameter can only accept owned strings, which limits how you can call it:
fn print_message(text: String) {
println!("{}", text);
}
// This works, but takes ownership
let my_string = String::from("Hello");
print_message(my_string); // my_string is no longer usable after thisHowever, a function that takes &str can accept both String references and string literals, making it much more versatile:
fn print_message(text: &str) {
println!("{}", text);
}
// Now you can call it with either type
let my_string = String::from("Hello");
print_message(&my_string); // Pass a reference to String
print_message("World"); // Pass a string literal directlyThis flexibility means your functions work in more situations without forcing callers to convert their data or give up ownership.
Challenge
EasyYou will receive two inputs. The first input is a text message, and the second input is the maximum length allowed for the message. Create a function called truncate_message that takes a string slice (&str) and a maximum length (usize) as parameters. If the message length exceeds the maximum, the function should return a slice of the message up to the maximum length. Otherwise, it should return the entire message. Print the result.
Requirements:
- Read the first input (the text message) and trim whitespace
- Read the second input (the maximum length) and trim whitespace
- Parse the maximum length to
usize - Define a function
truncate_messagethat takes two parameters:- A string slice
&strfor the message - A
usizefor the maximum length
- A string slice
- Inside the function, check if the message length is greater than the maximum length
- If yes, return a slice of the message from index 0 to the maximum length using
&message[0..max_len] - If no, return the entire message
- Call the function with the input message and maximum length
- Print the returned result
Input:
- First line: A text message (e.g.,
Hello World from Rust) - Second line: Maximum length as a number (e.g.,
11)
Output:
- The truncated message if it exceeds the maximum length, or the full message otherwise
Cheat sheet
Using &str as a parameter type makes functions more flexible than using String, as they can accept both string references and string literals:
fn print_message(text: &str) {
println!("{}", text);
}
let my_string = String::from("Hello");
print_message(&my_string); // Pass a reference to String
print_message("World"); // Pass a string literal directlyTo return a slice of a string up to a certain length, use slice syntax:
&message[0..max_len]Try it yourself
use std::io;
// TODO: Define the truncate_message function here
fn main() {
// Read the text message
let mut message = String::new();
io::stdin().read_line(&mut message).expect("Failed to read line");
let message = message.trim();
// Read the maximum length
let mut max_length_input = String::new();
io::stdin().read_line(&mut max_length_input).expect("Failed to read line");
let max_len: usize = max_length_input.trim().parse().expect("Invalid number");
// TODO: Call the truncate_message function and store the result
// TODO: Print the result
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
The 'match' ExpressionMatching Multiple ValuesMatching RangesThe 'if let' ExpressionLoops as ExpressionsRecap - Simple Command Parser4Grouping Data with Structs
What is a Struct?Structs OverviewAccessing Struct FieldsMutable StructsStructs as Function ParametersTuple StructsRecap - Create a Book Struct7Handling Errors with 'Result'
What is a 'Result'?Using 'match' with 'Result'is_ok() and is_err()Shortcuts: unwrap and expectThe Question Mark Operator '?'Parsing Strings to NumbersRecap - Safe Division Function10Closures & Anonymous Functions
What is a Closure?Defining a Simple ClosureClosures with ParametersCapturing the EnvironmentRecap - Simple Adder Closure2Introduction to Vectors
What is a Vector?Creating a VectorAdding Elements with pushAccessing Vector ElementsIterating Over a VectorMutable IterationRemoving ElementsRecap - Basic Score Tracker5Key-Value Pairs with Hash Maps
What is a Hash Map?Creating a Hash MapInserting Key-Value PairsAccessing ValuesIterating Over a Hash MapUpdating a ValueRemoving a PairRecap - Word Counter8Project: Simple Item Inventory
Project SetupAdding an ItemChecking StockSelling an ItemPutting it all together6Handling Absence with 'Option'
What is an 'Option'?Using 'match' with 'Option'is_some() and is_none()Unwrapping an 'Option'The expectProviding a Default: unwrap_orRecap - Find an Element9String Slices and More
String vs. &strCreating String SlicesSlices as Function ParametersOther SlicesRecap - Find First Word