Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Go CookBook
Go CookBook

Go CookBook: Top techniques and practical solutions for real-life Go programming problems

Arrow left icon
Profile Icon Burak Serdar
Arrow right icon
Coming Soon Coming Soon Publishing in Dec 2024
€18.99 per month
eBook Dec 2024 1st Edition
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Burak Serdar
Arrow right icon
Coming Soon Coming Soon Publishing in Dec 2024
€18.99 per month
eBook Dec 2024 1st Edition
Subscription
Free Trial
Renews at €18.99p/m
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Info icon
You can access this book only when it is published in Dec 2024
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Go CookBook

Working with Strings

String is one of the fundamental data types in Go.

Go uses immutable UTF-8-encoded strings. This might be confusing for a new developer; after all, this works:

x:="Hello"
x+=" World"
fmt.Println(x)
// Prints Hello World

Didn’t we just change x? Yes, we did. What is immutable here are the "Hello" and " World" strings. So, the string itself is immutable, but the string variable, x, is mutable. To modify string variables, you create slices of bytes or runes (which are mutable), work with them, and then convert them back to a string.

UTF-8 is the most common encoding used for web and internet technologies. This means that any time you deal with text in a Go program, you deal with UTF-8 strings. If you have to process data in a different encoding, you first translate it to UTF-8, process it, and encode it back to its original encoding.

UTF-8 is a variable-length encoding that uses one to four bytes for each...

Creating strings

In this recipe, we will look at how to create strings in a program.

How to do it...

  • Use a string literal. There are two types of string literals in Go:
    • Use interpreted string literals, between the double quotations:
      x := "Hello world"
    • With interpreted string literals, you must escape certain characters:
      x:="This is how you can include a \" in your string literal"
      y:="You can also use a newline \n, tab \t"
    • You can include Unicode codepoints or hexadecimal bytes, escaped with '\':
      w:="\u65e5本\U00008a9e"
      x:="\xff"

You cannot have newlines or an unescaped double-quote in an interpreted string:

  • Use raw string literals, using backticks. A raw string literal can include any characters (including newlines) except a backtick. There is no way to escape backticks in a raw literal.
    x:=`This is a
    multiline raw string literal.
    Backslash will print as backslash \`

If you need to include...

Formatting strings

The Go standard library offers multiple ways to substitute values in a text template. Here, we will discuss the text formatting utilities in the fmt package. They offer a simple and convenient way to substitute values in a text template.

How to do it...

  • Use the fmt.Print family of functions to format values
  • fmt.Print will print a value using its default formatting
  • A string value will be printed as is
  • A numeric value will be first converted to a string as an integer, a decimal number, or by using scientific notation for large exponents
  • A Boolean value will be printed as true or false
  • Structured values will be printed as a list of fields

If a Print function ends with ln (such as fmt.Println), a new line will be output after the string.

If a Print function ends with f, the function will accept a format argument, which will be used as the template into which it will substitute values.

fmt.Sprintf will format a string and return...

Combining strings

The Go standard library offers multiple ways to build strings from components. The best way depends on what type of strings you are dealing with, and how long they are. This section shows several ways that strings can be built.

How to do it...

  • To combine a few fixed numbers of strings, or to add runes to another string, use the + or += operators or string.Builder
  • To build a string algorithmically, use strings.Builder
  • To combine a slice of strings, use strings.Join
  • To combine parts of URL paths, use path.Join
  • To build filesystem paths from path segments, use filepath.Join

How it works...

To build constant values, or for simple concatenations, use the + or += operators:

var TwoLines = "This is the first line \n"+
"This is the second line"
func ThreeLines(newLine string) string {
   return TwoLines+"\n"+newLine
}

You can add runes to a string the same way:

func AddNewLine(line string...

Working with string cases

When working with textual data, problems related to string cases arise often. Should a text search be case-sensitive or case-insensitive? How do we convert a string to lowercase or uppercase? In this section, we will look at some recipes to deal with these common problems in a portable way.

How to do it...

  • Convert strings to uppercase and lowercase using the strings.ToUpper and strings.ToLower functions, respectively.
  • When dealing with text in languages with special uppercase/lowercase mappings (such as Turkish, where “İ” is the uppercase version of “I”), use strings.ToUpperSpecial and strings.ToLowerSpecial
  • To convert text to uppercase for use in titles, use strings.ToTitle
  • To compare strings lexicographically, use comparison operators
  • To test the equivalence of strings ignoring case, use strings.EqualFold

How it works...

Converting a string to uppercase or lowercase is easy:

greet...

Working with encodings

If there is a chance that your program will have to work with data produced by disparate systems, you should be aware of different text encodings. This is a huge topic, but this section should provide some pointers to scratch the surface.

How to do it...

  • Use the golang.org/x/text/encoding package to deal with different encodings.
  • To find an encoding by name, use one of the following:
    • golang.org/x/text/encoding/ianaindex
    • golang.org/x/text/encoding/htmlindex
  • Once you have an encoding, use it to translate text to and from UTF-8.

How it works...

Use one of the indexes to find an encoding. Then, use that encoding to read/write data:

package main
import (
     "fmt"
     "os"
     "golang.org/x/text/encoding/ianaindex"
)
func main() {
     enc, err := ianaindex.MIME.Encoding("US-ASCII")
  ...

Iterating bytes and runes of strings

Go strings can be seen as a sequence of bytes, or as a sequence of runes. This section shows how you can iterate a string either way.

How to do it...

To iterate the bytes of a string, use indexes:

for i:=0;i<len(str);i++ {
  fmt.Print(str[i]," ")
}

To iterate the runes of a string, use range:

for index, c:=range str {
  fmt.Print(c," ")
}

How it works...

A Go string is a slice of bytes, so you would expect to be able to write a for-loop to iterate the bytes and runes of a string. You might think that you can do the following:

strBytes := []byte(str)
strRunes := []rune(str)

However, converting a string to a slice of bytes or a slice of runes is an expensive operation. The first one creates a writeable copy of the bytes of the str string, and the second one creates a writeable copy of the runes of str. Remember that rune is uint32.

There are two forms of for-loop to iterate the...

Splitting

The strings package offers convenient functions to split a string to get a slice of strings.

How to do it...

  • To split a string into components using a delimiter, use strings.Split.
  • To split the space-separated components of a string, use strings.Fields.

How it works...

If you need to parse a string delimited with a fixed delimiter, use strings.Split. If you need to parse the space-separated sections of a string, use strings.Fields:

package main
import (
     "fmt"
     "strings"
)
func main() {
     fmt.Println(strings.Split("a,b,c,d", ","))
    // ["a", "b", "c", "d"]
     fmt.Println(strings.Split("a, b, c, d", ","))
    // ["a", " b", " c", " d"]
   &...

Reading strings line by line, or word by word

There are many use cases for processing strings in a stream, such as when dealing with large text or user input. This recipe shows the use of bufio.Scanner for this purpose.

How to do it...

  • Use bufio.Scanner for reading lines, words, or custom blocks.
  • Create a bufio.Scanner instance
  • Set the split method
  • Read scanned tokens in a for-loop

How it works...

The Scanner works like an iterator – every call to Scan() method will return true if it parsed the next token, or false if there are no more tokens. The token can be obtained by the Text() method:

package main
import (
     "bufio"
     "fmt"
     "strings"
)
const input = `This is a string
that has 3
lines.`
func main() {
     lineScanner := bufio.NewScanner(strings.NewReader(input))
     line...

Trimming the ends of a string

User input is usually messy, including additional spaces before or after the text that matters. This recipe shows how to use the string trimming functions for this purpose.

How to do it...

Use the strings.Trim family of functions, as shown here:

package main
import (
     "fmt"
     "strings"
)
func main() {
     fmt.Println(strings.TrimRight("Break-------", "-"))
    // Break
     fmt.Println(strings.TrimRight("Break with spaces-- -- --", "- "))
    // Break with spaces
     fmt.Println(strings.TrimSuffix("file.txt", ".txt"))
    // file
     fmt.Println(strings.TrimLeft(" \t   Indented text", " \t"))
    ...

Regular expressions

A regular expression offers efficient methods to ensure that textual data matches a given pattern, searches for patterns, extracts, and replaces parts of text. Usually, you compile a regular expression once and then use that compiled regular expression many times to efficiently validate, search, extract, or replace parts of strings.

Validating input

Format validation is the process of ensuring that data coming from user input or other sources is in a recognized format. Regular expressions can be an effective tool for such validation.

How to do it...

Use precompiled regular expressions to validate input values that should fit a pattern.

package main
import (
     "fmt"
     "regexp"
)
var integerRegexp = regexp.MustCompile("^[0-9]+$")
func main() {
     fmt.Println(integerRegexp.MatchString("123"))   // true
  ...

Extracting data from strings

You can use a regular expression to locate and extract text that occurs within a pattern.

How to do it...

Use capture groups to extract substrings that match a pattern.

How it works...

package main
import (
     "fmt"
     "regexp"
)
func main() {
     re := regexp.MustCompile(`^(\w+)=(\w+)$`)
     result := re.FindStringSubmatch(`property=12`)
     fmt.Printf("Key: %s value: %s\n", result[1], result[2])
     result = re.FindStringSubmatch(`x=y`)
     fmt.Printf("Key: %s value: %s\n", result[1], result[2])
}

Here is the output:

Key: property value: 12
Key: x value: y

Let’s look at this regular expression:

  • ^(\w+): A string composed of one or more word characters at the beginning of the line (capture group 1)
  • ...

Replacing parts of a string

You can use a regular expression to search through text, replacing parts that match a pattern with other strings.

How to do it...

Use the Replace family of functions to replace the patterns in a string with something else:

package main
import (
     "fmt"
     "regexp"
)
func main() {
     // Find numbers, capture the first digit
     re := regexp.MustCompile(`([0-9])[0-9]*`)
     fmt.Println(re.ReplaceAllString("This example replaces 
     numbers  with 'x': 1, 100, 500.", "x"))
    // This example replaces numbers  with 'x': x, x, x.
     fmt.Println(re.ReplaceAllString("This example replaces all 
     numbers with their first digits: 1, 100, 500...

Templates

Templates are useful for generating data-driven textual output. The text/template package can be used in the following contexts:

  • Configuration files: You can accept templates in configuration files, such as the following example that uses an env map variable to create environment-sensitive configurations
    logfile: {{.env.logDir}}/log.json
  • Reporting: Use templates to generate output for command-line applications and reports
  • Web applications: The html/template package provides HTML-safe templating functionality for template-based HTML generation to build web applications

Value substitution

The main use of templates is inserting data elements into structured text. This section describes how you can insert values computed in a program into a template.

How to do it...

Use the {{.name}} syntax to substitute a value in a template.

The following code segment executes a template using different inputs:

package main
import (
    ...

Dealing with empty lines

Template actions (i.e., the code elements placed in a template) may result in unwanted empty spaces and lines. The Go template system offers some mechanisms to deal with these unwanted spaces.

How to do it...

Use - next to the template delimiter:

  • {{- will remove all spaces/tabs/newlines that were output before this template element
  • -}} will remove all spaces/tabs/newlines that come after this template element

If a template directive produces output, such as the value of a variable, it will be written to the output stream. But if a template directive does not generate any output, such as a {{range}} or {{if}} statement, then it will be replaced with empty strings. And if those statements are on a line by themselves, those lines will be written to the output as well, like this:

{{range .}}
  {{if gt . 1}}
    {{.}}
  {{end}}
{{end}}

This template will produce an output every four lines. When...

Template composition

As templates grow, they may become repetitive. To reduce such repetition, the Go template system offers named blocks (components) that can be reused within a template, just like functions in a program. Then, the final template can be composed of these components.

How to do it...

You can create template “components” that you can reuse in multiple contexts. To define a named template, use the {{define "name"}} construct:

{{define "template1"}}
  ...
{{end}}
{{define "template2"}}
 ...
{{end}}

Then, call that template using the {{template "name" .}} construct as if it is a function with a single argument:

{{template "template1" .}}
{{range .List}}
  {{template "template2" .}}
{{end}}

How it works...

The following example prints a book list using a named template:

package main
import (
     "os"
    ...

Template composition – layout templates

When developing web applications, it is usually desirable to have a few templates specifying page layouts. Complete web pages are constructed by combining page components, developed as independent templates using this layout. Unfortunately, the Go template engine forces you to think of alternative solutions because Go template references are static. This means you would need a separate layout template for each page.

But there are alternatives.

I’ll show you a basic idea that demonstrates how template composition can be used so that you can extend it, based on your use case, or how to use an available third-party library that does this. The crucial idea in composition using layout templates is that if you define a new template using an already-defined template name, the new definition overrides the older one.

How to do it...

  • Create a layout template. Use empty templates or templates with default content for the sections...

There’s more...

The Go standard library documentation is always your best source for up-to-date information and great examples, such as the following:

The following links are also useful:

Left arrow icon Right arrow icon

Key benefits

  • Discover easy-to-implement recipes for all types of programming projects
  • Learn idiomatic solutions to common problems
  • Gain comprehensive knowledge of core Go concepts
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

With its simple syntax and sensible conventions, Go is an increasingly popular language favoured by devs in network programming, web services, data processing, and other settings. This book will help engineers leverage Go by providing up-to-date recipes with common solutions to many day-to-day problems. The book begins with the basics of code structure, describing different approaches to organizing packages for different types of projects. You'll then explore practical solutions to challenges you may encounter in your career, including areas such as network programming, dealing with processes, databases, data processing pipelines, and testing. You’ll also find working solutions and code snippets you can directly incorporate into your programs while working in sequential and concurrent settings. Solutions include more recent additions to the language, such as generics and structured logging. Most of the examples are developed using the Go standard library without any third-party packages. By the end of this book, you'll have a clear understanding of how to solve common programming problems using Go.

Who is this book for?

This book is for any developer with a basic understanding of the Go language. Senior developers can use it as a reference for finding useful examples they can apply to different use cases.

What you will learn

  • Understand how to structure projects
  • Find out how to process text with Go tools
  • Discover how to work with arrays, slices, and maps
  • Implement robust error handling patterns
  • Explore concurrent data processing for Go programs
  • Get up to speed with how to control processes
  • Integrate Go applications with databases
  • Understand how to test, benchmark, and profile Go programs

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 30, 2024
Edition : 1st
Language : English
ISBN-13 : 9781835464786
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Info icon
You can access this book only when it is published in Dec 2024
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Dec 30, 2024
Edition : 1st
Language : English
ISBN-13 : 9781835464786
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
Banner background image

Table of Contents

19 Chapters
Chapter 1: Project Organization Chevron down icon Chevron up icon
Chapter 2: Working with Strings Chevron down icon Chevron up icon
Chapter 3: Working with Date and Time Chevron down icon Chevron up icon
Chapter 4: Working with Arrays, Slices, and Maps Chevron down icon Chevron up icon
Chapter 5: Working with Types, Structs, and Interfaces Chevron down icon Chevron up icon
Chapter 6: Working with Generics Chevron down icon Chevron up icon
Chapter 7: Concurrency Chevron down icon Chevron up icon
Chapter 8: Errors and Panics Chevron down icon Chevron up icon
Chapter 9: The Context Package Chevron down icon Chevron up icon
Chapter 10: Working with Large Data Chevron down icon Chevron up icon
Chapter 11: Working with JSON Chevron down icon Chevron up icon
Chapter 12: Processes Chevron down icon Chevron up icon
Chapter 13: Network Programming Chevron down icon Chevron up icon
Chapter 14: Streaming Input/Output Chevron down icon Chevron up icon
Chapter 15: Databases Chevron down icon Chevron up icon
Chapter 16: Logging Chevron down icon Chevron up icon
Chapter 17: Testing, Benchmarking, and Profiling Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.