Problem overview
The function creating_ids receives a first name, first, and a last name, last, both as String. It returns an ID made of the first 2 letters of the first name followed by the last 3 letters of the last name. The first name has at least 2 letters, the last name at least 3, and both are English letters only.
For "John" and "Smith" the ID is "Joith". For "Jo" and "Doe" both names are used whole, giving "JoDoe". For "ada" and "Lovelace" the result is "adace": letters keep their case.
Approach
The ID is two slices glued together. The first slice starts at the beginning of first and is 2 letters long. The second ends at the end of last and is 3 letters long, so it starts 3 positions before the end, at last.len() - 3.
Both slices can be tried on their own. For "Smith" the length is 5, so last.len() - 3 is 2, and the slice from position 2 to the end is "ith". For "John" the slice 0..2 is "Jo". Putting them side by side gives "Joith".
The range for the start of the first name could also be written ..2, which means the same as 0..2. The lesson uses the explicit 0 so that both ends of the range are visible.
Step by step
- Slice the first name with the range
0..2. A range stops before its end, so this holds the letters at positions 0 and 1. - Slice the last name from
last.len() - 3to the end. Leaving out the end of a range means "up to the end of the string". - Join the two slices with
format!and two{}, and return the newString.
The solution in Rust
impl Solution {
fn creating_ids(first: String, last: String) -> String {
return format!("{}{}", &first[0..2], &last[last.len() - 3..]);
}
}
Some details worth knowing:
- Slices borrow. Both
&first[0..2]and&last[last.len() - 3..]are&strvalues that point into the original strings.format!copies their text into a newString. len()counts bytes. For English letters one byte is one letter, solast.len() - 3is the start of the last three letters. With letters likeé, which take two bytes, a slice could cut a letter in half, and Rust panics when that happens.- The subtraction is on a
usize.last.len()can't be negative, solast.len() - 3needs a length of at least 3. The lesson guarantees it.
Edge cases and common mistakes
- Names of exactly the required length.
"Jo"and"Doe"give0..2and0.., both whole names, so the ID is"JoDoe". - Off-by-one in the range.
0..3would take three letters from the first name:"Joh"for John. - Starting the second slice at the wrong place.
last.len() - 2..gives only two letters, andlast.len() - 4..gives four. - Changing the case. The ID keeps each letter as it is, so
"ada"stays lowercase. - Short last names. A last name with fewer than 3 letters would make
last.len() - 3go below zero. In a debug build that panics at the subtraction; in an optimized build the value wraps around to a huge number and the slice panics. The lesson rules this input out.
Testing
"John","Smith"gives"Joith"."Jo","Doe"gives"JoDoe"."ada","Lovelace"gives"adace".
