rodriggj / Go

0 stars 0 forks source link

1.10 What is the Raw String Literal #10

Open rodriggj opened 2 years ago

rodriggj commented 2 years ago

String Literals

In GO you can declare 2 types of string literals distinguished by what type of quotes (" ", ) you use:

  1. Double quotes or
  2. Backticks.

Double Quotes vs Backticks

What is the difference?

2 Primary Differences

  1. Multi-Line Text
    • [ ] A string literal (double quotes) CANNOT contain multiple lines of text.
    • [ ] Whereas a raw string literal (backticks) CAN contain multi-line text.
  2. Interpreted by the GO compiler
    • [ ] Using a string literal (double quotes) WILL be interpreted by GO. Example if an escape character is used it will be read and interpreted by GO.
    • [ ] Using a raw string literal is NOT interpreted by GO. Raw text values will be returned.
rodriggj commented 2 years ago

Example string literal

  1. In this example we show a few things with using a string literal vs. a raw sting literal
  2. First input the following code
    
    package main

import "fmt"

func main() { var s string s = "how are you?" s = how are you?

fmt.Println(s)

s = "<html>\n\t<body>\"Hello\"</body>\n</html>"
fmt.Println(s)

}


3. If we now run the code in the terminal 
```sh
go run main.go

Results in ...

image

Observation 1: We can reassign a string literal with a raw string literal. This is because both are of type string.

Observation 2:When we use double quotes to specify our string literal you can see in the terminal output that Go interprets things like escape characters and the format is therefore reflected this way in the output. (e.g. "\n" new line)

Observation 3: This form of "double quote" use to output an HTML string is very hard to read, understand, and maintain. In this instance you can see that it works; but using a raw string literal where multi-line use would probably help.

rodriggj commented 2 years ago

Example raw string literal

  1. If we make a modification to our main.go file to include a raw string literal then the code would look like this...
    
    package main

import "fmt"

func main() { var s string s = "how are you?" s = how are you?

fmt.Println(s)

s = "<html>\n\t<body>\"Hello\"</body>\n</html>"
fmt.Println(s)

s = `
"Hello"
`
fmt.Println(s)

}


> **Observation 1:** The `raw string literal` allows me to write the html code as it would normally appear in multi-line syntax as it would look in an editor. 

> **Observation 2:** The output of the 2 different syntax's is the same as you see in the console. 

2. When you run the main.go file 
```sh 
go run main.go

Results in ...

image

rodriggj commented 2 years ago

Use Cases

There may be several reasons to use on or the other; the most common considerations are:

  1. Will you require multi-line editing
  2. Will there be escape characters that need to be accounted for (e..g file path)