Help me please with enum and impl features

Hi everybody! I made a program which have two inner data strings and print true if 2nd is the end of 1st. Another way false. Help me please to redo it with that cool matches enum and impl, as in Book is.

// enum Enterlist {
//     FirstString(String),
//     SecondString(String),
// }


// impl Enterlist {
//     fn boo(&self) -> bool {
//         let len_firstS: u32 = &self.FirstString(String).len;
//     }
// }


fn main() {
    
    let first = String::from("qwerasdfd");
    let second = String::from("asdf");
    let index = first.len() - second.len();
    let last_first = &first[index..];
    let boo = last_first == second;

    println!("{}", boo);
} 

This isn't really a job for an enum. With an enum, you have exactly one of the variants for each value. But you need both the first and second strings at the same time.

So I suggest you go with:

struct Enterlist {
    first: String,
    second: String,
}

impl Enterlist {
    fn boo(&self) -> bool {
        todo!()
    }
}

The next thing to be aware of is that Rust strings are UTF8 encoded -- a single character (or Unicode scalar value) may take up multiple bytes -- but indexing is byte-based. Moreover, it's an error to slice (like first[index..]) into the middle of scalar value. Or in other words, breaking up strings takes some amount of care to do correctly. (Example.)

It's also an error to index out-of-bounds, and you don't know for sure that first is longer than second, either.

You could write all these required checks yourself, but usually you don't have to -- instead check the documentation for a method that does them for you. There is in fact one that does exactly what you want, but I'm going to go ahead and let you wrap up the exercise yourself.

2 Likes

let second = String::from("asdf"); here, you are missing "d".
Perhaps you meant
let second = String::from("asdfd");

I believe that’s what you need.

fn main() {
    let l1 = Enterlist::new("abc", "bc");
    let l2 = Enterlist::new("milk", "egg");
    assert_eq!(l1.boo(), true);
    assert_eq!(l2.boo(), false);
}

struct Enterlist {
    first: String,
    second: String,
}

impl Enterlist {
    pub fn new(first: &str, second: &str) -> Self {
        Self {
            first: first.to_owned(),
            second: second.to_owned(),
        }
    }

    pub fn boo(&self) -> bool {
        self.first.ends_with(&self.second)
    }
}
1 Like

Thank you very much guys!

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.