Wrapping my head around Rust (Part 2)
Sometimes, I factor my code out into functions (or methods) just to find the compiler complains about it.
Often, it happens because I try to return an Iterator or other Trait.
I’m still learning, but so far, I got these points about Rust functions:
- You can’t return traits from functions. Be specific, return something that implements the trait you need. For example, the return type “SplitWhitespace” from function “split_whitespace”. Very specific, right? But it implements “Iterator”. The function “split” returns the type “Split” a different struct that also implements “Iterator”. Useful link: implement iterator.
- You can accept traits as arguments, use and abuse that!
Rule of thumb, use the Postel’s law: “Be conservative in what you send, be liberal in what you accept”.