3 ms·
Many things aren't trivial, but some things are! For instance, the following is a program that uses a well-defined, user-friendly api for regex pattern matchin
by Dowwie 7y ago
Many things aren't trivial, but some things are! For instance, the following is a program that uses a well-defined, user-friendly api for regex pattern matching.
extern crate regex; // 1.1.8
fn main() {
let pattern = regex::Regex::new("(?i)resource not found").unwrap();
let msg = "resource not found".to_string(); // didn't have to convert to String as &str suffices
if pattern.is_match(&msg) {
println!("found pattern in msg");
} else {
println!("did not find pattern in msg");
}
}
Clearly, this is an easy example and when used in the wild, you'll have to account for error handling. However, whatever isn't trivial exists for a good reason. Trivial comes at a cost. One thing I like about Rust is that it lets a programmer decide what costs to assume.
- hu3 7y agoPerhaps we have different definitions of trivial but I don't find it trivial to cast a string to a string in variable declarations: let msg = "resource not found".to_string(); Is it necessary?
- steveklabnik 7y agoYou're not casting a string to a string, you're casting a &str to a String. > Is it necessary? In this code, it's not actually necessary, your parent converts it back to a &str later, when passing it to is_match. In other cases, it's very necessary; they're two different types, with different properties.
- hu3 7y agoThanks for explaining steve. I guess these things become second nature with practice.
- steveklabnik 7y agoYep! Rust has a few "rules of three" that appear again and again. This is an instance of there being three kinds of types: T, &T, and &mut T. That is, owned, borrowed, and mutably borrowed. In most examples of this, "T" is the same thing in all places, that is, i32, &i32, &mut i32, but in this case, "str" is built into the language. So you have String, &str, and &mut str. The naming is slightly off, because you're coming into the conflict of String being a standard library type, and str being a language type. We almost unified them before 1.0, but there wasn't a ton of benefit. The point is, yes, it is a bit confusing at first, you're totally right. I actually re-did the entire table of contents of The Rust Programming Language to re-focus them on strings due to this. But you're also right that after some practice, it's a non-issue that you never really spend mental effort on. The trick is, how many people will be willing to spend that time? Can we reduce that time? Time will tell :)
- Dowwie 7y agonope.