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
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Go Standard Library Cookbook
Go Standard Library Cookbook

Go Standard Library Cookbook: Over 120 specific ways to make full use of the standard library components in Golang

eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Go Standard Library Cookbook

Strings and Things

The recipes in this chapter are:

  • Finding the substring in a string
  • Breaking the string into words
  • Joining the string slice with a separator
  • Concatenating a string with writer
  • Aligning text with tabwriter
  • Replacing part of the string
  • Finding the substring in text by the regex pattern
  • Decoding a string from the non-Unicode charset
  • Controlling case
  • Parsing comma-separated data
  • Managing whitespace in a string
  • Indenting a text document

Introduction

Operations on strings and string-based data are common tasks in a developer's life. This chapter covers how to handle these using the Go standard library. It is no surprise that with the standard library it is possible to do a great deal.

Check whether Go is properly installed. The Getting ready section from the Retrieving the Golang version recipe of Chapter 1, Interacting with the Environment, will help you.

Finding the substring in a string

Finding the substring in a string is one of the most common tasks for developers. Most of the mainstream languages implement this in a standard library. Go is not an exception. This recipe describes the way Go implements this.

How to do it...

  1. Open the console and create the folder chapter02/recipe01.
  2. Navigate to the directory.
  3. Create the contains.go file with the following content:
        package main

import (
"fmt"
"strings"
)

const refString = "Mary had a little lamb"

func main() {

lookFor := "lamb"
contain := strings.Contains(refString, lookFor)
fmt.Printf("The \&quot...

Breaking the string into words

Breaking the string into words could be tricky. First, decide what the word is, as well as what the separator is, and if there is any whitespace or any other characters. After these decisions have been made, you can choose the appropriate function from the strings package. This recipe will describe common cases.

How to do it...

  1. Open the console and create the folder chapter02/recipe02.
  2. Navigate to the directory.
  3. Create the whitespace.go file with the following content:
        package main

import (
"fmt"
"strings"
)

const refString = "Mary had a little lamb"

func main() {

words := strings.Fields(refString...

Joining the string slice with a separator

The recipe, Breaking the string into words, led us through the task of splitting the single string into substrings, according to defined rules. This recipe, on the other hand, describes how to concatenate the multiple strings into a single string with a given string as the separator.

A real use case could be the problem of dynamically building a SQL select statement condition.

How to do it...

  1. Open the console and create the folder chapter02/recipe03.
  2. Navigate to the directory.
  3. Create the join.go file with the following content:
        package main

import (
"fmt"
"strings"
)

const selectBase = "SELECT * FROM user WHERE...

Concatenating a string with writer

Besides the built-in + operator, there are more ways to concatenate the string. This recipe will describe the more performant way of concatenating strings with the bytes package and the built-in copy function.

How to do it...

  1. Open the console and create the folder chapter02/recipe04.
  2. Navigate to the directory.
  3. Create the concat_buffer.go file with the following content:
       package main

import (
"bytes"
"fmt"
)

func main() {
strings := []string{"This ", "is ", "even ",
"more ", "performant "}
buffer := bytes.Buffer{}
for _, val...

Aligning text with tabwriter

In certain cases, the output (usually data output) is done via tabbed text, which is formatted in well-arranged cells. This format could be achieved with the text/tabwriter package. The package provides the Writer filter, which transforms the text with the tab characters into properly formatted output text.

How to do it...

  1. Open the console and create the folder chapter02/recipe05.
  2. Navigate to the directory.
  3. Create the tabwriter.go file with the following content:
        package main

import (
"fmt"
"os"
"text/tabwriter"
)

func main() {

w := tabwriter.NewWriter(os.Stdout, 15, 0, 1, ' ',
...

Replacing part of the string

Another very common task related to string processing is the replacement of the substring in a string. Go standard library provide the Replace function and Replacer type for the replacement of multiple strings at once.

How to do it...

  1. Open the console and create the folder chapter02/recipe06.
  2. Navigate to the directory.
  3. Create the replace.go file with the following content:
        package main

import (
"fmt"
"strings"
)

const refString = "Mary had a little lamb"
const refStringTwo = "lamb lamb lamb lamb"

func main() {
out := strings.Replace(refString, "lamb", "wolf", -1)
...

Finding the substring in text by the regex pattern

There are always tasks such as validating the input, searching the document for any information, or even cleaning up a given string from unwanted escape characters. For these cases, regular expressions are usually used.

The Go standard library contains the regexp package, which covers the operations with regular expressions.

How to do it...

  1. Open the console and create the folder chapter02/recipe07.
  2. Navigate to the directory.
  3. Create the regexp.go file with the following content:
        package main

import (
"fmt"
"regexp"
)

const refString = `[{ \"email\": \"email@example.com\" \
...

Decoding a string from the non-Unicode charset

A lesser-known fact is that all content in .go files is encoded in UTF-8. Believe it or not the Unicode is not, the only charset in the world. For example, the Windows-1250 encoding is widely spread across Windows users.

When working with non-Unicode strings, you need to transcode the content to Unicode. This recipe demonstrates how to decode and encode the non-Unicode strings.

How to do it...

  1. Open the console and create the folder chapter02/recipe08.
  2. Navigate to the directory.
  3. Create the file win1250.txt with content Gdańsk. The file must be encoded in the windows-1250 charset. If you are not sure how to do that, just jump to step 6 and after you complete step 7, which...

Controlling case

There are a lot of practical tasks where the modification of case is the most common approach. Let's pick a few of these:

  • Case-insensitive comparison
  • Beginning the sentence with an automatic first capital
  • Camel-case to snake-case conversion

For these purposes, the strings package offers functions ToLower, ToUpper, ToTitle, and Title.

How to do it...

  1. Open the console and create the folder chapter02/recipe09.
  2. Navigate to the directory.
  3. Create the case.go file with the following content:
        package main

import (
"fmt"
"strings"
"unicode"
)

const email = "ExamPle@domain.com"
const name = "isaac newton...

Parsing comma-separated data

There are multiple table data formats. CSV (comma-separated values) is one of the most basic formats largely used for data transport and export. There is no standard that defines CSV, but the format itself is described in RFC 4180.

This recipe introduces how to parse CSV-formatted data comfortably.

How to do it...

  1. Open the console and create the folder chapter02/recipe10.
  2. Navigate to the directory.
  3. Create a file named data.csv with the following content:
        "Name","Surname","Age"
# this is comment in data
"John","Mnemonic",20
Maria,Tone,21
  1. Create the data.go file with the following content:
        package main

...

Managing whitespace in a string

The string input could contain too much whitespace, too little whitespace, or unsuitable whitespace chars. This recipe includes tips on how to manage these and format the string to your needs.

How to do it...

  1. Open the console and create the folder chapter02/recipe11.
  2. Navigate to the directory.
  3. Create a file named whitespace.go with the following content:
        package main

import (
"fmt"
"math"
"regexp"
"strconv"
"strings"
)

func main() {

stringToTrim := "\t\t\n Go \tis\t Awesome \t\t"
trimResult := strings.TrimSpace(stringToTrim)
fmt.Println...

Indenting a text document

The previous recipe depicts how to do string padding and whitespace trimming. This one will guide you through the indentation and unindentation of a text document. Similar principles from the previous recipes will be used.

How to do it...

  1. Open the console and create the folder chapter02/recipe12.
  2. Create the file main.go with the following content:
         package main

import (
"fmt"
"strconv"
"strings"
"unicode"
)

func main() {

text := "Hi! Go is awesome."
text = Indent(text, 6)
fmt.Println(text)

text = Unindent(text, 3)
fmt.Println...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Develop high quality, fast and portable applications by leveraging the power of Go Standard Library.
  • Practical recipes that will help you work with the standard library algorithms to boost your productivity as a Go developer.
  • Compose your own algorithms without forfeiting the simplicity and elegance of the Standard Library.

Description

Google's Golang will be the next talk of the town, with amazing features and a powerful library. This book will gear you up for using golang by taking you through recipes that will teach you how to leverage the standard library to implement a particular solution. This will enable Go developers to take advantage of using a rock-solid standard library instead of third-party frameworks. The book begins by exploring the functionalities available for interaction between the environment and the operating system. We will explore common string operations, date/time manipulations, and numerical problems. We'll then move on to working with the database, accessing the filesystem, and performing I/O operations. From a networking perspective, we will touch on client and server-side solutions. The basics of concurrency are also covered, before we wrap up with a few tips and tricks. By the end of the book, you will have a good overview of the features of the Golang standard library and what you can achieve with them. Ultimately, you will be proficient in implementing solutions with powerful standard libraries.

Who is this book for?

This book is for Go developers who would like to explore the power of Golang and learn how to use the Go standard library for various functionalities. The book assumes basic Go programming knowledge.

What you will learn

  • Access environmental variables
  • Execute and work with child processes
  • Manipulate strings by performing operations such as search, concatenate, and so on
  • Parse and format the output of date/time information
  • Operate on complex numbers and effective conversions between different number formats and bases
  • Work with standard input and output
  • Handle filesystem operations and file permissions
  • Create TCP and HTTP servers, and access those servers with a client
  • Utilize synchronization primitives
  • Test your code

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 27, 2018
Length: 340 pages
Edition : 1st
Language : English
ISBN-13 : 9781788391672
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Feb 27, 2018
Length: 340 pages
Edition : 1st
Language : English
ISBN-13 : 9781788391672
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

Frequently bought together


Stars icon
Total 107.97
Go Standard Library Cookbook
€41.99
Distributed Computing with Go
€32.99
Security with Go
€32.99
Total 107.97 Stars icon

Table of Contents

12 Chapters
Interacting with the Environment Chevron down icon Chevron up icon
Strings and Things Chevron down icon Chevron up icon
Dealing with Numbers Chevron down icon Chevron up icon
Once Upon a Time Chevron down icon Chevron up icon
In and Out Chevron down icon Chevron up icon
Discovering the Filesystem Chevron down icon Chevron up icon
Connecting the Network Chevron down icon Chevron up icon
Working with Databases Chevron down icon Chevron up icon
Come to the Server Side Chevron down icon Chevron up icon
Fun with Concurrency Chevron down icon Chevron up icon
Tips and Tricks Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
(1 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 100%
Leam Hall Oct 15, 2018
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Really didn't get fully past the first chapter. The author has an engaging style and if Packt had done a decent job editing and fixing this could be a classic. When contacted they wanted me to spend time logging all their problems for free. Since there were more than a dozen in Chapter 1 I figured it wasn't worth the time.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.