Rust Function: Borrow String Slice, Get first character
Rust Ownership, Borrowing, and Lifetimes: Exercise-8 with Solution
Write a Rust function that borrows a string slice and returns its first character.
Sample Solution:
Rust Code:
// Define a function named 'get_first_char' that borrows a string slice and returns its first character
fn get_first_char(s: &str) -> Option<char> {
s.chars().next() // Return an Option containing the first character of the string slice, or None if the string is empty
}
fn main() {
let my_string = "Hello, world!"; // Define a string slice
// Call the 'get_first_char' function and pass a reference to 'my_string' to borrow it
match get_first_char(&my_string) {
Some(first_char) => {
println!("First character of the string: {}", first_char);
}
None => {
println!("The string is empty.");
}
}
// 'my_string' is still accessible here because we only borrowed it
println!("Used 'my_string' after borrowing: {}", my_string);
}
Output:
First character of the string: H Used 'my_string' after borrowing: Hello, world!
Explanation:
Here is a brief explanation of the above Rust code:
- fn get_first_char(s: &str) -> Option<char> { ... }: This is a function named get_first_char that borrows a string slice (&str) and returns an Option
. The function returns 'Some' containing the first character of the string slice if it exists, or 'None' if the string is empty. The parameter 's' is of type '&str', indicating borrowing. - Inside the function:
- We use the "chars()" method to obtain an iterator over the characters of the string slice.
- We use the "next()" method to retrieve the first character of the iterator, which returns an 'Option<char>'.
- In the main function,
- Define a string slice named 'my_string'.
- We then call the "get_first_char()" function and pass a reference to my_string (&my_string) to borrow it.
- We match on the result:
- If "Some", we print the value of the first character.
- If 'None', we print a message indicating that the string is empty.
- 'my_string' remains accessible after borrowing because we only borrowed it and didn't transfer ownership.
Rust Code Editor:
Previous: Rust Function: Borrow Slice, Calculate Sum.
Next: Rust Function: Double Vector length, Ownership transfer.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/rust/basic/rust-ownership-borrowing-and-lifetimes-exercise-8.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics