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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to Czechia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

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 : 9781787125643
Vendor :
Google
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Czechia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Publication date : Sep 26, 2017
Length: 466 pages
Edition : 1st
Language : English
ISBN-13 : 9781787125643
Vendor :
Google
Category :
Languages :
Tools :

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

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela