Open rodriggj opened 2 years ago
string literal
string literal
vs. a raw sting literal
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 ...
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.
raw string literal
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 ...
There may be several reasons to use on or the other; the most common considerations are:
String Literals
In GO you can declare 2 types of string literals distinguished by what type of quotes (" ",
) you use:
Double Quotes vs Backticks
string literal
`), you are declaring a
raw string literal`What is the difference?
2 Primary Differences
string literal
(double quotes) CANNOT contain multiple lines of text.raw string literal
(backticks) CAN contain multi-line text.string literal
(double quotes) WILL be interpreted by GO. Example if an escape character is used it will be read and interpreted by GO.raw string literal
is NOT interpreted by GO. Raw text values will be returned.