10 ms·
The lazy_static macro (provided by a third party crate) allows you to create static (global, basically singleton pattern) variables that get initialized on firs
by est31 8y ago
The lazy_static macro (provided by a third party crate) allows you to create static (global, basically singleton pattern) variables that get initialized on first use and then are being reused over and over again.
The "lazy ref" is part of that macro's syntax. "msg_break" is the name of the static variable. Then, in Rust, all static things must have type annotations. In this case, it's the "TwoWaySearcher<'static>". The "TwoWaySearcher::new("\r\n\r\n".as_bytes())" is the initializer code that's being only called once. The as_bytes function is solely a type casting operation to convert from a str for which the typesystem guarantees that it's utf-8 formatted to a byte slice that just represents arbitrary data.
- ajross 8y agoActually I sort of knew all that (though it was the first time I'd seen lazy_static! and had to infer it from context). The question was more about "why"? Again in C the equivalent is literally a string literal. There's really no easier way to express "double newline" in Rust than this thing which requires that the reader parse a "lazy static", a parametrized type, an explicit type conversion and a library utility? Why not?
- est31 8y agoThis thing is so bulky because the API that TwoWaySearcher has is so bulky. You could also have a very simple API that just takes a string literal. It's less a problem of Rust and more of that TwoWaySearcher struct.
- coldtea 8y ago>There's really no easier way to express "double newline" in Rust than this thing which requires that the reader parse a "lazy static", a parametrized type, an explicit type conversion and a library utility? Why not? The code doesn't express 'double newline'. That would be just the "\r\n\r\n".as_bytes() The code lazily initializes an TwoWaySearcher to parse such double newlines.
- steveklabnik 8y agoAlso note that b”” is nicer than .as_bytes()