Golang String Literal Examples (Repeat Method)

Use string literals with double-quotes and the tick character. Specify repeating string literals.

String literals. Often programs need to have string data specified within the programs themselves. This data is usually in the form of string literals.Strings

With the best syntax, we can make our programs easier to read. Raw string literals in Golang use tick characters. Regular expressions often benefit from raw literals.

Syntax example. Go supports 2 syntaxes for string literals. With regular quotes, special sequences like newlines are interpreted as actual newlines.
Raw: With the backtick character, escape sequences are ignored. The chars are treated as normal values.
Golang program that uses string literals, raw literals package main import "fmt" func main() { // The newline sequence is treated as a special value. value1 := "cat\ndog" fmt.Println(value1) // The newline sequence is treated as two raw chars. value2 := `cat\ndog` fmt.Println(value2) } Output cat dog cat\ndog

Repeat. With the Repeat func we can repeat a string. The first argument is the string we want to repeat, and the second is the count of repetitions.
Tip: For creating repeating text, using Repeat() with a string literal is a good solution.
Golang program that uses Repeat package main import ( "fmt" "strings" ) func main() { // Create a new string based on a repetition. result := strings.Repeat("abc...", 3) fmt.Println(result) } Output abc...abc...abc...

A summary. String literal syntax can improve a program's readability. With Repeat() and the best literal syntax form, programs are easier to read—and this will tend to lead to fewer bugs.

© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.