Raw strings are handy when you’re working with content that has characters that would normally require escaping in a regular string. For instance, if you’re dealing with HTML, raw strings can save you from the headache of messing up the original HTML structure.
Raw strings starts with r#
and closes with a #
like so: r#""#
. Here is an example of a Javascript code being passed as a string using the raw string syntax:
fn main() {
let string = r"#
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
})
);
});
#";
println!("{}", string.len());// 216
}
Assuming you have a bunch of string in a file and you’ll like to import them as-is, a nice method to achieve this is thestd::fs::read_to_string
which is used to read the contents of a file and turn them into a string.
Here’s an example of how the read_to_string
method works:
fn main() {
if let Ok(contents) = fs::read_to_string("example.txt") {
println!("{}", contents);
}
}
Happy Hacking!