Code review for str split

Here's my code

struct Split<'reminder, 'delimiter> {
    reminder: &'reminder str,
    delimiter: &'delimiter str,
}

impl<'reminder, 'delimiter> Split<'reminder, 'delimiter> {
    pub fn new(reminder: &'reminder str,
               delimiter: &'delimiter str,) -> Self {
        if let Some(index) = reminder.find(delimiter) {
            //it is to check if the delimiter appears in the first character
            if index == 0 {
                //then remove that character
                return Split { reminder: &reminder[(delimiter.len())..], delimiter };
            }
        }
        Split { reminder, delimiter }
    }
}

impl<'reminder, 'delimiter> Iterator for Split<'reminder, 'delimiter> {
    type Item = &'reminder str;

    fn next(&mut self) -> Option<Self::Item> {
        if self.reminder.is_empty() {
            None
        } else if let Some(index) = self.reminder.find(self.delimiter) {
            let until_delimiter = &self.reminder[..index];
            self.reminder = &self.reminder[(index+ self.delimiter.len())..];
            Some(until_delimiter)
        } else {
            let val = Some(self.reminder);
            self.reminder = "";
            val
        }
    }
}

#[cfg(test)]
pub mod tests {
    use super::Split;
    #[test]
    fn basics() {
        let arr: Vec<&str> = Split::new("πŸ‘πŸ‘abcπŸ‘πŸ‘cdeπŸ‘defπŸ‘", "πŸ‘").collect();
        assert_eq!(arr, vec! ["", "abc", "", "cde", "def"]);
    }
}

I tried moving the logic of checking if the first character is a delimiter to impl block. but, I'm finding it really hard. Whatever solution I come up with either looks very ugly, or fail the test case. So, how to do it so it would fit nicely with other conditions?

I think you need the explicit return because there is no else clause.

You can perhaps move the logic of checking if the first character is a delimiter into the impl block of Iterator

A block consists of a sequence of statements optionally followed an expression. There are two ways that a function can return:

  • when an explicit return expression is evaluated, it directly returns the relevant value;

  • when control flow falls to the end of the function, the result of the trailing expression in the function body is returned (or () if there is no trailing expression).

1 Like

I tried moving the first character logic to impl block. but, I'm finding it really hard. Whatever solution I come up with either looks very ugly, or fail the test case. I'm kind of stuck there. I'll update the above topic to reflect the issue

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.