Golang String Operations
Go provides a rich set of functiontionality for working with strings. This guide covers various ways to define and operate on strings in Go, including building multi-line strings, reading and writing text files, and printing Go structs.
Defining Multiline Strings
The preferred way to write a string that spans multiple lines is to use a raw string literal, which is enclosed by backticks. Raw string literals preserve the newlines and any other special characters within the string. All whitespace is also preserved as-is, so pay attention to indentation!
package main
import "fmt"
func main() {
s := `This is a
multiline
string`
fmt.Println(s)
}
This is a
multiline
string
Try this in the Go playground here (opens in a new tab).
Reading and Writing Files
Go provides a simple way to read and write entire files using the os.ReadFile (opens in a new tab) and os.WriteFile (opens in a new tab) functions. These functions work with byte slices, so you'll need to convert the data to and from strings when working with text files.
These functions were added to Go in version 1.16, obsoleting the ioutil.ReadFile
and ioutil.WriteFile
functions that were previously used for this purpose.
Because these functions read and write entire files at once, they are not suitable
for very large files. For those cases, you should use the os.Open
and os.Create
functions instead to work with the data in smaller chunks.
The following example writes a string to a file and then reads it back.
package main
import (
"fmt"
"os"
)
func main() {
// Write a file
err := os.WriteFile("test.txt", []byte("Don't Panic."), 0644)
if err != nil {
fmt.Println(err)
}
// Read a file
data, err := os.ReadFile("test.txt")
if err != nil {
fmt.Println(err)
}
fmt.Println(string(data))
}
Don't Panic.
Try this in the Go playground here (opens in a new tab).
String Manipulation Functions
Go's standard library includes the strings
package, which is packed with
useful string manipulation utilities. Here are some of the most commonly used functions:
strings.Contains(s, substr)
: Returns true if the strings
contains the substringsubstr
.strings.Split(s, sep)
: Splits the strings
into a slice of substrings separated by the separatorsep
.strings.Join(slice, sep)
: Concatenates the items in a slice into a single string using the separatorsep
.strings.Trim(s, cutset)
: Removes all leading and trailing characters contained incutset
froms
.strings.ReplaceAll(s, old, new)
: Replaces all occurrences ofold
ins
withnew
.
Here are some examples of using these functions:
package main
import (
"fmt"
"strings"
)
func main() {
// Contains
fmt.Println(strings.Contains("hello world", "world")) // true
// Split
parts := strings.Split("hello,world,go", ",")
fmt.Println(parts) // [hello world go]
// Join
joined := strings.Join(parts, "-")
fmt.Println(joined) // hello-world-go
// Trim
trimmed := strings.Trim("Hello, World!", "!")
fmt.Println(trimmed) // Hello, World
// Replace
replaced := strings.ReplaceAll("hello world", "world", "gopher")
fmt.Println(replaced) // hello gopher
}
Try this in the Go playground here (opens in a new tab).
Printing Go Structs
Go provides a convenient way to print structs using the %+v
format verb with
the fmt.Printf
function. This verb prints the struct's field names and values.
It's a useful tool for debugging or inspecting the contents of a struct.
package main
import "fmt"
type Person struct {
Name string
Age int
Email string
}
func main() {
p := Person{
Name: "John Doe",
Age: 30,
Email: "[email protected]",
}
fmt.Printf("%+v\n", p)
}
{Name:John Doe Age:30 Email:[email protected]}
Try this in the Go playground here (opens in a new tab).