Showing posts with label HTML. Show all posts
Showing posts with label HTML. Show all posts

Tuesday, February 2, 2021

Raw String Literals in Go

Learn what are Raw String Literals in Go and how to use them

On a previous posts we discussed Runes, Variables and Strings in Go. Today, let's continue our study of Go Strings by learning about raw string literals.

    Raw String Literals

    Raw string literals are character sequences between back quotes, as in `foo`. Within raw string literals, no escape sequences are processed; the contents are taken literally. For example:

    s := `{
    "name": "john"
    }`
    fmt.Println(s)

    Prints:

    {
    "name": "john"
    }

    Particularities of raw string literals

    Here are a few particularities of raw string literals:

    • within the quotes any character can appear except from back quote (`)
    • the value of a raw string literal is the string composed of the uninterpreted (implicitly UTF-8-encoded) characters between the quotes
    • the string may contain newlines
    • carriage return characters ('\r') are discarded
    • no escape sequences are processed; the contents are taken literally
    • a raw string literal may spread over several lines in the source code

    When to use raw string literals

    Due to its preservation of  format and disabled escaping nature, raw string literals are convenient in multiple contexts, including:

    • writing regular expressions
    • HTML templates
    • JSON literals
    • command usage messages
    • XML
    • YAML
    • and other formats that require preservation of the formatting
    We'll see uses of raw string literals for each of the above cases. Keep tuned!

    Conclusion

    On this post we learned a little more about Strings in Go by reviewing raw string literals. Since manipulating Strings is an essential part of a programmer's life, understanding their particularities is important to master the Go programming language.

      Source

      See Also

      Any comment about this page? Please contact us on Twitter

      Featured Article

      Pointers in Go

      Understand all about declaring and using pointers in Go If you're coming from Python, Java, JavaScript, C# and others, tal...

      Popular Posts