Raw String in Rust

Raw String in Rust

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!

Buy Me A Coffee

Published by Eze Sunday Eze

Hi, welcome to my blog. I am Software Engineer and Technical Writer. And in this blog, I focus on sharing my views on the tech and tools I use. If you love my content and wish to stay in the loop, then by all means share this page and bookmark this website.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.