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

Arrow left icon
Profile Icon Radomír Sohlich
Arrow right icon
Free Trial
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1 (1 Ratings)
Paperback Feb 2018 340 pages 1st Edition
eBook
Can$38.99 Can$55.99
Paperback
Can$69.99
Subscription
Free Trial
Arrow left icon
Profile Icon Radomír Sohlich
Arrow right icon
Free Trial
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1 (1 Ratings)
Paperback Feb 2018 340 pages 1st Edition
eBook
Can$38.99 Can$55.99
Paperback
Can$69.99
Subscription
Free Trial
eBook
Can$38.99 Can$55.99
Paperback
Can$69.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
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 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 : 9781788475273
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
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 : Feb 27, 2018
Length: 340 pages
Edition : 1st
Language : English
ISBN-13 : 9781788475273
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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 Can$6 each
Feature tick icon Exclusive print discounts
$279.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 Can$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Can$ 181.97
Go Standard Library Cookbook
Can$69.99
Distributed Computing with Go
Can$55.99
Security with Go
Can$55.99
Total Can$ 181.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

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.