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 Systems Programming
Go Systems Programming

Go Systems Programming: Master Linux and Unix system level programming with Go

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 Systems Programming

Writing Programs in Go

This chapter will talk about many essential, interesting, and handy Go topics that will help you be more productive. I think it would be a good idea to start this chapter by compiling and running the Go code of the hw.go program from the previous chapter. Then, you will learn how to deal with the environment variables that can be used by Go, how to process the command-line arguments of a Go program, and how to print the output on the screen and get input from the user. Finally, you will see how to define functions in Go, learn about the extremely important defer keyword, look at the data structures that come with Go, and learn what Go interfaces are before checking out code that generates random numbers.

Therefore, in this chapter, you will become familiar with many Go concepts, including the following:

  • Compiling your Go programs
  • Go environment variables...

Compiling Go code

Go does not care about the name of the source file of an autonomous program as long as the package name is main and there is a main() function in it. This is because the main() function is where the program execution begins. This also means that you cannot have multiple main() functions in the files of a single project.

There exist two ways to run a Go program:

  • The first one, go run, just executes the Go code without generating any new files, only some temporary ones that are deleted afterward
  • The second way, go build, compiles the code, generates an executable file, and waits for you to run the executable file

This book is written on an Apple Mac OS Sierra system using the Homebrew (https://brew.sh/) version of Go. However, you should have no difficulties compiling and running the presented Go code on most Linux and FreeBSD systems, provided that you have...

Go environment variables

The go tool can use many Unix shell environment variables dedicated to Go, including GOROOT, GOHOME, GOBIN, and GOPATH. The most important Go environment variable is GOPATH, which specifies the location of your workspace. Usually, this is the only environment variable that you will need to define when developing Go code; it is to do with the way the files of a project will be organized. This means that each project will be organized into three main directories, named src, pkg, and bin. However, many people, including me, prefer not to use GOPATH and manually organize their project files.

So, if you are a big fan of shell variables, you can put all these kinds of definitions in either .bashrc or .profile, which means that these environment variables will be active every time you log in to your Unix machine. If you are not using the Bash shell, which is...

Using command-line arguments

Command-line arguments allow your programs to get input, such as the names of the files you want to process, without having to write a different version of the program. Hence, you cannot create any useful systems software if you're unable to process the command-line arguments passed to it.

So here is a naive Go program, named cla.go, that prints all its command-line arguments, including the name of the executable file:

package main 
 
import "fmt" 
import "os" 
 
func main() { 
   arguments := os.Args 
   for i := 0; i < len(arguments); i++ { 
         fmt.Println(arguments[i]) 
   } 
} 

As you can see, Go needs an extra package named os in order to read the command-line arguments of a program that are stored in the os.Args array. In case you do not like having multiple import statements, you can rewrite the two import statements...

User input and output

According to the Unix philosophy, when a program finishes its job successfully, it generates no output. However, for a number of reasons, not all programs finish successfully and they need to inform the user about their issues by printing appropriate messages. Additionally, some system tools need to get input from the user in order to decide how to handle a situation that might come up.

The hero of Go user input and output is the fmt package, and this section is going to show you how to perform these two tasks by starting with the simplest one.

The best place to learn more about the fmt package is its documentation page, which can be found at https://golang.org/pkg/fmt/.

Getting user input

Apart from...

Go functions

Functions are an important element of every programming language because they allow you to break big programs into smaller and more manageable parts, but they must be as independent of each other as possible and must do one job and only one job. So, if you find yourself writing functions that do multiple things, you may want to consider writing multiple functions instead. However, Go will not refuse to compile functions that are long, complicated, or do multiple things.

A safe indication that you need to create a new function is when you find yourself using the same Go code multiple times in your program. Similarly, a safe indication that you need to put some of your functions in a module is when you find yourself using the same functions all the time in most of your programs.

The single most popular Go function is main(), which can be found in every autonomous Go...

Go data structures

Go comes with many handy data structures that can help you store your own data, including arrays, slices, and maps. The most important task that you should be able to perform on any data structure is accessing all of its elements in some way. The second important task is having direct access to a specific element once you know its index or key. The last two equally important tasks are inserting elements and deleting elements from data structures. Once you know how to perform these four tasks, you will have complete control over the data structure.

Arrays

Arrays are the most popular data structure due to their speed and are supported by almost all programming languages. You can declare an array in Go as follows...

Interfaces

Interfaces are an advanced Go feature, which means that you might not want to use them in your programs if you are not feeling very comfortable with Go. However, interfaces can be very practical when developing big Go programs, which is the main reason for talking about interfaces in this book.

But first, I will talk about methods, which are functions with a special receiver argument. You declare methods as ordinary functions with an additional parameter that appears just before the function name. This particular parameter connects the function to the type of that extra parameter. As a result, that parameter is called the receiver of the method. You will see such functions in a while.

Put simply, interfaces are abstract types that define a set of functions that need to be implemented so that a type can be considered an instance of the interface. When this happens, we...

Creating random numbers

As a practical programming example, this section will talk about creating random numbers in Go. Random numbers have many uses, including the generation of good passwords as well as the creation of files with random data that can be used for testing other applications. However, bear in mind that usually programming languages generate pseudorandom numbers that approximate the properties of a true random number generator.

Go uses the math/rand package for generating random numbers and needs a seed to start producing random numbers. The seed is used for initializing the entire process and is extremely important because if you always start with the same seed, you will always get the same sequence of random numbers.

The random.go program has three main parts. The first part is the preamble of the program:

package main 
 
import ( 
   "fmt" 
   &quot...

Exercises

  1. Browse the Go documentation site: https://golang.org/doc/.
  2. Write a Go program that keeps reading integers until you give the number 0 as input, then it prints the minimum and maximum integer in the input.
  3. Write the same Go program as before, but this time, you will get your input using command-line arguments. Which version do you think is better? Why?
  4. Write a Go program that supports two command-line options (-i and -k) in random order using if statements. Now change your program to support three command-line arguments. As you will see, the complexity of the latter program is just too much to handle using if statements.
  5. If the indices of a map were natural numbers, are there any cases that it would be wise and efficient to use a map instead of an array?
  6. Try to put the functionality of array2map.go into a separate function.
  7. Try to develop your own random number generator...

Summary

You learned many things in this chapter, including getting user input and processing command-line arguments. You familiarized yourself with the basic Go structures and you created a Go program that generates random numbers. Try to do the offered exercises and do not get discouraged if you fail in some of them.

The next chapter will talk about many advanced Go features, including error handling, pattern matching, regular expressions, reflection, unsafe code, calling C code from Go, and the strace(1) command-line utility. I will compare Go with other programming languages and give you practical advice in order to avoid some common Go pitfalls.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • - Learn how to write system's level code in Golang, similar to Unix/Linux systems code
  • - Ramp up in Go quickly
  • - Deep dive into Goroutines and Go concurrency to be able to take advantage of Go server-level constructs

Description

Go is the new systems programming language for Linux and Unix systems. It is also the language in which some of the most prominent cloud-level systems have been written, such as Docker. Where C programmers used to rule, Go programmers are in demand to write highly optimized systems programming code. Created by some of the original designers of C and Unix, Go expands the systems programmers toolkit and adds a mature, clear programming language. Traditional system applications become easier to write since pointers are not relevant and garbage collection has taken away the most problematic area for low-level systems code: memory management. This book opens up the world of high-performance Unix system applications to the beginning Go programmer. It does not get stuck on single systems or even system types, but tries to expand the original teachings from Unix system level programming to all types of servers, the cloud, and the web.

Who is this book for?

Intermediate Linux and general Unix programmers. Network programmers from beginners to advanced practitioners. C and C++ programmers interested in different approaches to concurrency and Linux systems programming.

What you will learn

  • •Explore the Go language from the standpoint of a developer conversant with Unix, Linux, and so on
  • • Understand Goroutines, the lightweight threads used for systems and concurrent applications
  • • Learn how to translate Unix and Linux systems code in C to Golang code
  • • How to write fast and lightweight server code
  • • Dive into concurrency with Go
  • • Write low-level networking code

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 26, 2017
Length: 466 pages
Edition : 1st
Language : English
ISBN-13 : 9781787123151
Vendor :
Google
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 : Sep 26, 2017
Length: 466 pages
Edition : 1st
Language : English
ISBN-13 : 9781787123151
Vendor :
Google
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 120.97
Machine Learning With Go
€41.99
Go Systems Programming
€41.99
Learning Functional Programming in Go
€36.99
Total 120.97 Stars icon
Banner background image

Table of Contents

12 Chapters
Getting Started with Go and Unix Systems Programming Chevron down icon Chevron up icon
Writing Programs in Go Chevron down icon Chevron up icon
Advanced Go Features Chevron down icon Chevron up icon
Go Packages, Algorithms, and Data Structures Chevron down icon Chevron up icon
Files and Directories Chevron down icon Chevron up icon
File Input and Output Chevron down icon Chevron up icon
Working with System Files Chevron down icon Chevron up icon
Processes and Signals Chevron down icon Chevron up icon
Goroutines - Basic Features Chevron down icon Chevron up icon
Goroutines - Advanced Features Chevron down icon Chevron up icon
Writing Web Applications in Go Chevron down icon Chevron up icon
Network Programming Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.4
(8 Ratings)
5 star 25%
4 star 12.5%
3 star 37.5%
2 star 25%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Evaggelos Balaskas Oct 24, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is a must have on your library!Initially I had my reservations about Go and this book (as I am not a developer/programmer), but after the first few chapters I was completely overturned by it!The author, without wasting any time -this is a not a beginners book-, immediately jumps to the point and you can really start writing Go code from the very first chapters. And this comes from a sysadmin who somehow was afraid to write any Go code before.It only took a few chapters playing with the code examples to see that. The chapters were enlightening and while reading the book I had the feeling that it was written for someone like me. Overall, this is a book of great quality, that you will use it again as a reference in the future.
Amazon Verified review Amazon
No name Oct 28, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a very nice book for those who know basic programming and they want to learn systems programming but also for those who are programmers and they are interested in learning Go.There are many examples that help the understanding of basic Go concepts and the way that things are done in Go. It also explains the basics of Unix and system programming in Unix.
Amazon Verified review Amazon
George Adamopoulos Oct 23, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I really like Go. I am replacing C with it in most of my choices. The fact that it comes "batteries includes" and that it has endured the last 10 years helps. So I really needed a book that would allow me to view it more as a tool than just a language.This is such a book. This is a book where you already know some Go (i.e. you have read the tutorial that is available at gopl.io). But it is also a book that is not self-contained, in that if you do know know enough Go, you need to use your web browser a lot. For example to lookup more stuff about reflections. Or some other packages that get imported.It is clear that the author did not intend to write yet another introduction to Go. The target audience is people who armed with a terminal and an editor are more interested in tooling. Stuff that in the "old days" you would decide to write in C. Now here is a path to write them in Go. This is the great achievement of the book. You go through it section by section and if you have any significant systems programming experience with C, you feel the relevance: "I've done this in C before! So that's how you do it in Go". And it is not about C. Scripting in any of your language of choice can at times be done in Go also.If you do not have time pressure, the sections are small enough that you can work one or two of them per day. That would be a slow progress, but it would also be a 10 minute per day plan.To learn Go, I would go through and introduction to the language (among the numerous ones available), then work this book and finally keep the GoPL at bay for reference.There have been typos which I have submitted to the author of the book and I read it on O'Reilly's Safari
Amazon Verified review Amazon
Ranx0r0x Jun 15, 2018
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
The book starts with a rather obtuse and scattershot introduction to Go. Not enough to actually learn Go programming so it isn't a tutorial but it isn't terribly useful.The book doesn't really start until getting into File and processes and then it ends to quickly with a web applications section that seems tacked on. It isn't that any of it is particularly bad but if it is going to be a "Systems Programming" book then it should focus on systems programming and not programming basics of pointers, structs, installation, version numbers and the like and swerve sharply later into setting up a web server with database back end.
Amazon Verified review Amazon
Greg Nov 26, 2017
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Easy start but even tho the author included a lot of code and commands I had to google a lot in order to follow along with the examples. Maybe his compile command does work but because the book's formatting is off, I had to google for it. Plus, the author omits saying in the text what the following commands will do so he missed his chance to clarify things.
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.