0% found this document useful (0 votes)
114 views165 pages

Go Book

An introduction to programming in go By Caleb Doxsey. this is small but with all the topics great book.

Uploaded by

gkgoswami987
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
114 views165 pages

Go Book

An introduction to programming in go By Caleb Doxsey. this is small but with all the topics great book.

Uploaded by

gkgoswami987
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 165
AN INTRODUCTION TO PROGRAMMING CALEB DOXSEY An Introduction to Programming in Go Copyright © 2012 by Caleb Doxsey All rights reserved. No part of this book may be reproduced or transmitted in any form or by any means, electronic or mechanical, _ including photocopying, recording, or by any information storage and retrieval system without the written permission of the author, except where permitted by law. ISBN: 978-1478355823 Cover art by Abigail Doxsey Anderson. Portions of this text are reproduced from work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License, Contents 1 Getting Started 1.1 Files and Folders 1.2 The Terminal 1.3 Text Editors 1.4 Go Tools 2 Your First Program 2.1 How to Read a Go Program 3 Types 3.1 Numbers 3.2 Strings 8.3 Booleans 4 Variables 4.1 How to Name a Variable 4.2. Scope 4.3 Constants 4.4 Defining Multiple Variables 4.5 An Example Program 5 Control Structures 5.1 For bait 5.3 Switch 6 Arrays, Slices and Maps 6.1 Arrays 6.2 Slices 6.3 Maps 7 Functions 7.1 Your Second Funet 7.2 Returning Multiple Values 7.3 Variadic Functions we 13 16 7 23 24 29 31 7.4 Closure 7.5 Recursion 7.6 Defer, Panic & Recover 8 Pointers 8.1 The * and & operators B.2new 9 Struets and Interfaces 9.1 Structs 9.2 Methods 9.3 Interfaces 10 Concurrency 10.1 Goroutines 10.2 Channels 11 Packages 11.1 Creating Packages 11.2 Documentation 12 Testing 13 The Core Packages 13.1 Strings 13.2 Input / Output 13.3 Files & Folders 13.4 Errors 13.5 Containers & Sort 13.6 Hashes & Cryptography 13.7 Servers 13.8 Parsing Command Line Arguments 13.9 Synchronization Primitives 14 Next Steps 14.1 Study the Masters 14.2 Make Something 14.3 Team Up 84 86 88 92 93 94 97 98 101 104 108 108 ut 120 121 124 127 132 132 134 135 140 141 44 47 156 159 159 160 161 1 Getting Started Computer programming is the art, craft and science of writing programs which define how computers operate. This book will teach you how to write computer pro- grams using a programming language designed by Google named Go. Go is a general purpose programming language with advanced features and a clean syntax. Because of its wide availability on a variety of platforms, its robust well-documented common library, and its focus on good software engineering principles, Go is an ideal lan- guage to learn as your first programming language. The process we use to write software using Go (and most programming languages) is fairly straightfor- ward: 1. Gather requirements 2. Finda solution 3. Write source code to implement the solution Getting Started 2 4. Compile the source code into an executable 5. Run and test the program to make sure it works This process is iterative (meaning its done many times) and the steps usually overlap. But before we write our first program in Go there are a few prerequi- site concepts we need to understand. 1.1 Files and Folders A file is a collection of data stored as a unit with a name. Modern operating systems (like Windows or Mac OSX) contain millions of files which store a large variety of different types of information — everything from text documents to executable programs to multi- media files. All files are stored in the same way on a computer: they all have a name, a definite size (measured in bytes) and an associated type. Typically the file's type is signified by the file's extension — the part of the file name that comes after the last .. For example a file with the name hello. txt has the extension txt which is used to represent textual data. Folders (also called directories) are used to group files together. They can also contain other folders. On Win- 8 Getting Started dows file and folder paths (locations) are represented with the \ (backslash) character, for example: €:\Users\john\example.txt. example.txt is the file name, it is contained in the folder john, which is itself contained in the folder Users which is stored on drive C (which represents the primary physical hard drive in Windows). On OSX (and most other operating systems) file and folder paths are represented with the / (for- ward slash) character, for example: Jusers/john/example.txt. Like on — Windows example.txt is the file name, it is contained in the folder john, which is in the folder Users. Unlike Win- dows, OSX does not specify a drive letter where the file is stored. Getting Started 4 Windows On Windows files and folders can be browsed using Windows Explorer (accessible by double-clicking “My Computer” or typing win+e): LUbraries 5 Gotting Started Osx On OSX files and folders can be browsed using Finder (accessible by clicking the Finder icon — the face icon in the lower left bar): Gud = & B Qremereie rare ent 1.2 The Terminal Most of the interactions we have with computers today are through sophisticated graphical user interfaces (GUIs). We use keyboards, mice and touchscreens to interact with visual buttons or other types of controls that are displayed on a screen. It wasn't always this way. Before the GUI we had the terminal — a simpler textual interface to the computer Getting Started 6 where rather than manipulating buttons on a screen we issued commands and received replies. We had a conversation with the computer. And although it might appear that most of the comput- ing world has left behind the terminal as a relic of the past, the truth is that the terminal is still the funda- mental user interface used by most programming lan- guages on most computers. The Go programming lan- guage is no different, and so before we write a program in Go we need to have a rudimentary understanding of how a terminal works, Windows In Windows the terminal (also known as the command line) can be brought up by typing the windows key +r (hold down the windows key then press 1), typing cnd.exe and hitting enter. You should see a black win- dow appear that looks like this: Getting Started By default the command line starts in your home di- rectory. (In my case this is €:\Users\caleb) You issue commands by typing them in and hitting enter. Try en- tering the command dir, which lists the contents of a directory. You should see something like this: C:\Users\caleb>dir Volume in drive C has no label. Volume Serial Number is B2F5-F125 Followed by a list of the files and folders contained in your home directory. You can change directories by us- ing the command cd. For example you probably have a folder called Desktop. You can see its contents by enter- ing €d Desktop and then entering dir. ‘To go back to your home directory you can use the special directory name .. (two periods next to each other): cd... A sin- gle period represents the current folder (known as the working folder), so cd . doesn’t do anything. There are Getting Started 8 a lot more commands you can use, but this should be enough to get you started. osx In OSX the terminal can be reached by going to Finder = Applications + Utilities + Terminal. You should see a window like this: alt By default the terminal starts in your home directory. (In my case this is /Users/caleb) You issue commands by typing them in and hitting enter. Try entering the command 1s, which lists the contents of a directory. You should see something like this: 9 Getting Started caleb-min:~ caleb$ 1s Desktop Downloads Movies Pictures Documents Library Music Public ‘These are the files and folders contained in your home directory (in this case there are no files). You can change directories using the cd command. For example you probably have a folder called Desktop. You can see its contents by entering cd Desktop and then entering Is. ‘To go back to your home directory you can use the special directory name .. (two periods next to each other): cd... A single period represents the current folder (known as the working folder), so cd . doesn't do anything. There are a lot more commands you can use, but this should be enough to get you started, 1.3 Text Editors ‘The primary tool programmers use to write software is a text editor. Text editors are similar to word process- ing programs (Microsoft Word, Open Office, like such programs they don't do any formatting, (No bold, italic, ...) instead they operate only on plain text. Both OSX and Windows come with text editors but they are highly limited and I recommend installing a better one. but un- ‘To make the installation of this software e2 ier an in- Getting Started 10 staller is available at the book's website: http: //www.golang-book.com/. This installer will in- stall the Go tool suite, setup environmental variables and install a text editor. Windows For windows the installer will install the Seite text ed- itor. You can open it by going to Start + All Programs = Go + Scite. You should see something like this: The text editor contains a large white text area where text can be entered. To the left of this text area you can see the line numbers. At the bottom of the window is a oa Getting Started status bar which displays information about the file and your current location in it (right now it says that we are on line 1, column 1, text is being inserted nor- mally, and we are using windows-style newlines). You can open files by going to File + Open and brows- ing to your desired file, Files can be saved by going to Fille + Save or File + Save As. As you work in a text editor it is useful to learn key- board shortcuts. The menus list the shortcuts to their right. Here are a few of the most common: + Ctrl + S—save the current file + Ctrl + X—cut the currently selected text (remove it and put it in your clipboard so it can be pasted later) + Ctrl + C copy the currently selected text + Ctrl +V-paste the text currently in the clipboard + Use the arrow keys to navigate, Home to go to the beginning of the line and End to go to the end of the line + Hold down shift while using the arrow keys (or Home and End) to select text without using the mouse + Ctrl + F— brings up a find in file dialog that you can use to search the contents of a file Getting Started 12 osx For OSX the installer installs the Text Wrangler text editor: untitled text > (Fa), Mew Documen) <1 ona tet 8.) 1 [1 Tinone) “# [Unieede UTF=8) = [unacaH)= 11 07077 Like Scite on Windows Text Wrangler contains a large white area where text is entered. Files can be opened by going to File + Open. Files can be saved by going to File Save or File + Save As. Here are some useful keyboard shorteuts: (Command is the 88 key) 18 Getting Started + Command + $ — save the current file + Command + X - cut the currently selected text (re- move it and put it in your clipboard so it can be pasted later) + Command + C — copy the currently selected text + Command + V— paste the text currently in the clip- board + Use the arrow keys to navigate + Command + F — brings up a find in file dialog that you can use to search the contents of a file 1.4 Go Tools Go is a compiled programming language, which means souree code (the code you write) is translated into a language that your computer can understand, There- fore before we can write a Go program, we need the Go compiler, ‘The installer will setup Go for you automatically. We will be using version 1 of the language. (More informa- tion can be found at http://www. golang.org) Let's make sure everything is working. Open up a ter- minal and type the following: go version Getting Started 4 ‘You should see the following: go version gol.0.2 Your version number may be slightly different. If you get an error about the command not being recognized try restarting your computer. ‘The Go tool suite is made up of several different com- mands and sub-commands. A list of those commands is available by typing: go help We will see how they are used in subsequent chapters. 2 Your First Program ‘Traditionally the first program you write in any pro- gramming language is called a “Hello World” program — a program that simply outputs Hello World to your terminal. Let's write one using Go. First create a new folder where we can store our pro- gram. The installer you used in chapter 1 created a folder in your home directory named Go. Create a folder named ~/Go/src/golang-book/chapter2. (Where ~ means your home directory) From the terminal you can do this by entering the following commands: Go/src/golang-book Go/src/golang-book/chapter2 Using your text editor type in the following: 15 Your First Program 16 package main import “fmt™ J this is a comment func main() { fmt.PrintIn("Hello World") + Make sure your file is identical to what is shown here and save it as main.go in the folder we just created. Open up a new terminal and type in the following: cd Go/src/golang-book/chapter2 go run main.go You should see Hello World displayed in your terminal. ‘The go run command takes the subsequent files (sep- arated by spaces), compiles them into an executable saved in a temporary directory and then runs the pro- gram. If you didn't see Hello World displayed you may have made a mistake when typing in the program. The Go compiler will give you hints about where the mis- take lies. Like most compilers, the Go compiler is ex- tremely pedantic and has no tolerance for mistakes. I Your First Program 2.1 How to Read a Go Program Let's look at this program in more detail. Go programs are read top to bottom, left to right. (like a book) The first line says this: package main This is known as a “package declaration”. Every Go program must start with a package declaration. Pack- ages are Go's way of organizing and reusing code. There are two types of Go programs: executables and libraries. Executable applications are the kinds of pro- grams that we can run directly from the terminal. (in Windows they end with .exe) Libraries are collections of code that we package together so that we can use them in other programs. We will explore libraries in more detail later, for now just make sure to include this line in any program you write. ‘The next line is a blank line. Computers represent newlines with a special character (or several charac- ters). Newlines, spaces and tabs are known as white- space (because you can't see them). Go mostly doesn't care about whitespace, we use it to make programs easier to read. (You could remove this line and the pro- gram would behave in exactly the same way) Your First Program 18 Then we see this: import “fmt The import keyword is how we include code from other packages to use with our program. The fmt package (shorthand for format) implements formatting for in- put and output. Given what we just learned about packages what do you think the fmt package's files would contain at the top of them? Notice that fmt above is surrounded by double quotes. The use of double quotes like this is known as a “string literal” which is a type of “expression”. In Go strings represent a sequence of characters (letters, numbers, symbols, ...) of a definite length. Strings are described in more detail in the next chapter, but for now the im- portant thing to keep in mind is that an opening * character must eventually be followed by another * character and anything in between the two is included in the string. (The " character itself is not part of the string) The line that starts with // is known as a comment. Comments are ignored by the Go compiler and are there for your own sake (or whoever picks up the source code for your program). Go supports two differ- 19 Your First Program ent styles of comments: // comments in which all the text between the // and the end of the line is part of the comment and /* */ comments where everything between the #s is part of the comment. (And may in- clude multiple lines) After this you see a function declaration: func main() { fmt.PrintIn("Hello World") + Functions are the building blocks of a Go program. ‘They have inputs, outputs and a series of steps called statements which are executed in order, All functions start with the keyword func followed by the name of the function (main in this case), a list of zero or more “parameters” surrounded by parentheses, an optional return type and a “body” which is surrounded by curly braces, This function has no parameters, doesn't re- turn anything and has only one statement. The name nnain is special because it's the function that gets called when you execute the program. ‘The final piece of our program is this line: fmt.Print1n("Hello World") Your First Program 20 This statement is made of three components. First we access another function inside of the fmt package called Printin (that's the fmt.Println piece, Println means Print Line). Then we create a new string that contains Hello World and invoke (also known as call or execute) that function with the string as the first and only argument. At this point we've already seen a lot of new terminol- ogy and you may be a bit overwhelmed. Sometimes its helpful to deliberately read your program out loud. One reading of the program we just wrote might go like this: Create a new executable program, which references the fmt library and contains one function called main. That function takes no arguments, doesn’t re- turn anything and does the following: Access the Println function contained inside of the mt pack- age and invoke it using one argument ~ the string Hello World, The PrintIn function does the real work in this pro- gram. You can find out more about it by typing the fol- lowing in your terminal: godoc fmt Printin 21 Your First Program Among other things you should see this: PrintIn formats using the default formats for its operands and writes to standard output. Spaces are always added between operands and a newline is appended. It returns the number of bytes written and any write error encountered. Go is a very well documented programming language but this documentation can be difficult to understand unless you are already familiar with programming lan- guages. Nevertheless the godoe command is extremely useful and a good place to start whenever you have a question. Back to the function at hand, this documentation is telling you that the Println function will send what- ever you give to it to standard output — a name for the output of the terminal you are working in. This func- tion is what causes Hello World to be displayed, In the next chapter we will explore how Go stores and represents things like Hello World by learning about types. Your First Program 22 Problems . What is whitespace? What is a comment? What are the two ways of writing a comment? Our program began with package main. What would the files in the fmt package begin with? We used the Printin function defined in the fmt package. If we wanted to use the Exit function from the os package what would we need to do? Modify the program we wrote so that instead of printing Hello World it prints Hello, my name is followed by your name. 3 Types In the last chapter we used the data type string to store Hello World. Data types categorize a set of re- lated values, describe the operations that can be done on them and define the way they are stored. Since types can be a difficult concept to grasp we will look at them from a couple different perspectives before we see how they are implemented in Go. Philosophers sometimes make a distinction between types and tokens. For example suppose you have a dog named Max. Max is the token (a particular instance or member) and dog is the type (the general concept). “Dog” or “dogness” describes a set of properties that all dogs have in common. Although oversimplistie we might reason like this: All dogs have 4 legs, Max is a dog, therefore Max has 4 legs. Types in programming languages work in a similar way: All strings have a length, x is a string, therefore x has a length. In mathematies we often talk about sets. For example: R(the set of all real numbers) or IN(the set of all natu- ral numbers). Each member of these sets shares prop- 23 ‘Types a erties with all the other members of the set. For exam- ple all natural numbers are associative: “for all natu- ral numbers a, b, and ¢, a + (b +c) = (a+b) +e and ax (b x ) = (a xb) X c.” In this way sets are similar to types in programming languages since all the values of a particular type share certain properties. Go is a statically typed programming language. This means that variables always have a specific type and that type cannot change. Static typing may seem cum- bersome at first. You'll spend a large amount of your time just trying to fix your program so that it finally compiles. But types help us reason about what our pro- gram is doing and catch a wide variety of common mis- takes. Go comes with several built-in data types which we will now look at in more detail. 3.1 Numbers Go has several different types to represent numbers. Generally we split numbers into two different kinds: integers and floating-point numbers. Integers Integers — like their mathematical counterpart — are 25 ‘Types numbers without a decimal component. (..., -3, -2,-1, 0, 1, ...) Unlike the base-10 decimal system we use to represent numbers, computers use a base-2 binary sys- tem, Our system is made up of 10 different digits. Once we've exhausted our available digits we represent larger numbers by using 2 (then 3, 4, 5, ...) digits put next to each other. For example the number after 9 is 10, the number after 99 is 100 and so on. Computers do the same, but they only have 2 digits instead of 10. So counting looks like this: 0, 1, 10, 11, 100, 101, 110, 111 and so on. The other difference between the num- ber system we use and the one computers use is that all of the integer types have a definite size. They only have room for a certain number of digits. So a 4 bit in- toger might look like this: 0000, 0001, 0010, 0011, 0100. Eventually we run out of space and most com- puters just wrap around to the beginning. (Which can result in some very strange behavior) Go's integer types are: uint8, uint16, uint32, uinted, int8, int16, int32 and int64. 8, 16, 32 and 64 tell us how many bits each of the types use. uint means “un- igned integer” while int means “signed integer”. Un- signed integers only contain positive numbers (or zero). In addition there two alias types: byte which is the same as uint8 and rune which is the same as ‘Types 26 int32. Bytes are an extremely common unit of mea- surement used on computers (1 byte = 8 bits, 1024 bytes = 1 kilobyte, 1024 kilobytes = 1 megabyte, ...) and therefore Go's byte data type is often used in the definition of other types. There are also 3 machine de- pendent integer types: uint, int and uintptr. They are machine dependent because their size depends on the type of architecture you are using. Generally if you are working with integers you should just use the int type. Floating Point Numbers Floating point numbers are numbers that contain a decimal component (real numbers). (1.234, 123.4, 0.00001234, 12340000) ‘Their actual representation on a computer is fairly complicated and not really neces- sary in order to know how to use them. So for now we need only keep the following in mind: 1. Floating point numbers are inexact. Occasion- ally it is not possible to represent a number. For example computing 1.01 - 0.99 results in @.02¢000000000000018 - A number extremely close to what we would expect, but not exactly the same. 27 ‘Types 2, Like integers floating point numbers have a cer- tain size (32 bit or 64 bit). Using a larger sized floating point number increases it's precision. (how many digits it can represent) 3, In addition to numbers there are several other values which can be represented: “not a num- ber” (NaN, for things like @/@) and positive and negative infinity. (4 and -») Go has two floating point types: float32 and floatea (also often referred to as single precision and double precision respectively) as well as two additional types for representing complex numbers (numbers with imaginary parts): complex64 and conplex128. Generally we should stick with floatea when working with float- ing point numbers. Example Let's write an example program using numbers. First create a folder called chapter3 and make a main.go file containing the following: ‘Types 28 package main import “fmt™ func main() { fmt.Println("1 +1 =", 1+ 1) + If you run the program and you should see this: $ go run main.go 141-2 Notice that this program is very similar to the pro- gram we wrote in chapter 2. It contains the same pack- age line, the same import line, the same function dee- Jaration and uses the same Println function. This time instead of printing the string Hello World we print the string 1 + 1 = followed by the result of the expression 1 + 1. This expression is made up of three parts: the numeric literal 1 (which is of type int), the + operator (which represents addition) and another numeric lit- eral 1. Let's try the same thing using floating point numbers: fmt.Println("1 +1 =", 1.0 + 1.0) Notice that we use the .@ to tell Go that this is a float- 29 ‘Types ing point number instead of an integer. Running this program will give you the same result as before. In addition to addition Go has several other operators: + [addition + [subtraction multiplication /_ |division % remainder 3.2 Strings As we saw in chapter 2 a string is a sequence of char- acters with a definite length used to represent text. Go strings are made up of individual byt for each character. (Characters from other languages like Chinese are represented by more than one byte) es, usually one String literals can be created using double quotes “Hello World" or back ticks “Hello World’. The differ- ence between these is that double quoted strings can- not contain newlines and they allow special escape quences. For example \n gets replaced with a newline and \t gets replaced with a tab character. ‘Types 30 Several common operations on strings include finding the length of a string: len("Hello World"), accessing an individual character in the string: "Hello World"[1], and concatenating two strings together: "Hello " + “World”. Let's modify the program we cre- ated earlier to test these out: package main import “fmt func main() { fmt. Print1n(1en("Hello World") fmt.Print1n("Hello World"[1]) fmt.Print1n("Hello * + "World") A few things to notice: 1. A space is also considered a character, so the string’s length is 11 not 10 and the 3 line has “Hello “ instead of "Hello". 2. Strings are “indexed” starting at 0 not 1. [1] gives you the 2" element not the 1". Also notice that you see 101 instead of e when you run this program. This is because the character is repre- sented by a byte (remember a byte is an integer). 31 3.3 ‘Types One way to think about indexing would be to show it like this instead: "Hello World"; You'd read that as “The string Hello World sub 1,” “The string Hello World at 1” or “The second character of the string Hello World”. Concatenation uses the same symbol as addi- tion. The Go compiler figures out what to do based on the types of the arguments. Since both sides of the + are strings the compiler assumes you mean concatenation and not addition. (Ad- dition is meaningless for strings) Booleans A boolean value (named after George Boole) is a spe- cial 1 bit integer type used to represent true and false (or on and off). Three logical operators are used with boolean values: 8a land lor not Here is an example program showing how they can be ‘Types 32 used: func main() { fmt.PrintIn(true 8& true) fmt.PrintIn(true && false) fmt.PrintIn(true || true) fmt.PrintIn(true || false) fmt. Print1n(!true) Running this program should give you: $ go run main.go true false true true false ‘We usually use truth tables to define how these opera- tors work: Expression | Value true && true | true true && false | false false && true | false false & false | false ‘Types 38 Expression _| Value true || true true true || false | true false || true | true false || false | false Expression | Value Ttrue false false true These are the simplest types included with Go and form the foundation from which all later types are built, ‘Types 34 Problems 1. How are integers stored on a computer? 2. We know that (in base 10) the largest 1 digit number is 9 and the largest 2 digit number is 99. Given that in binary the largest 2 digit num- ber is 11 (3), the largest 3 digit number is 111 (7) and the largest 4 digit number is 1111 (15) what's the largest 8 digit number? (hint: 10°-1 = 9 and 10*-1 = 99) 3. Although overpowered for the task you can use Go as a calculator. Write a program that com- putes 32132 x 42452 and prints it to the termi- nal. (Use the * operator for multiplication) 4, What is a string? How do you find its length? 5. What's the value of the expression (true && false) || (false && true) || !(false && false)? 4 Variables Up until now we have only seen programs that use lit- eral values (numbers, strings, ete.) but such programs aren't particularly useful. To make truly useful pro- grams we need to learn two new concepts: variables and control flow statements. This chapter will explore variables in more detail. A variable is a storage location, with a specific type and an associated name. Let's change the program we wrote in chapter 2 so that it uses a variable: package main import "fmt" func main() { var x string = fmt. Print1n(x) Hello World” Notice that the string literal from the original program still appears in this program, but rather than send it directly to the Printin function we assign it to a vari- 85 Variables 36 able instead. Variables in Go are created by first using the var keyword, then specifying the variable name (x), the type (string) and finally assigning a value to the variable (Hello World). The last step is optional so an alternative way of writing the program would be like this: package main import "fmt" func main() { var x string x = "Hello World” fmt. Print1n(x) Variables in Go are similar to variables in algebra but there are some subtle differen: First when we see the = symbol we have a tendency to read that as “x equals the string Hello World’. There's nothing wrong with reading our program that way, but it's better to read it as “x takes the string Hello World’ or “x is assigned the string Hello World’. This distine- tion is important because (as their name would sug- gest) variables can change their value throughout the lifetime of a program. Try running the following: 387 Variables package main import “fmt func main() { var x string x = "first" fmt. Print1n(x) x = "second" fmt Printin(x) In fact you can even do this: var x string x= "first " fmt. Print1n(x) x = x + “second” fmt PrintIn(x) ‘This program would be nonsense if you read it like an algebraic theorem. But it makes sense if you are care- ful to read the program as a list of commands. When we see x the concatenation of the value of the variable x and the string literal second to the variable x.” The right side of the = is done first and the result is then assigned to the left side of the x + "second" we should read it as “assign ‘The x = x + y form is so common in programming that Variables 38 Go has a special assignment statement: 42. We could have written x = x + "second" as x += "second" and it would have done the same thing. (Other operators can be used the same way) Another difference between Go and algebra is that we (Two equal is an operator like + and it use a different symbol for equality: signs next to each other) returns a boolean, For example: "hello “world” y) var x string var y string fmt. Print1n(x This program should print false because hello is not the same as world. On the other hand: var x string = "hello var y string = "hello" fmt.PrintIn(x == y) This will print true because the two strings are the same. Since creating a new variable with a starting value is s0 common Go also supports a shorter statement: 39 Variables Hello World" Notice the : before the = and that no type was speci. fied. The type is not necessary because the Go compiler is able to infer the type based on the literal value you assign the variable. (Since you are assigning a string literal, x is given the type string) The compiler can also do inference with the var statement: var x = “Hello World” ‘The same thing works for other types: x i= 5 fmt. Println(x) Generally you should use this shorter form whenever possible. 4.1 How to Name a Variable Naming a variable properly is an important part of software development. Names must start with a letter and may contain letters, numbers or the _ (underscore) symbol. The Go compiler doesn't care what you name a variable so the name is meant for your (and others) Variables 40 benefit. Pick names which clearly describe the vari- able's purpose. Suppose we had the following: Xie "Max" fmt.PrintIn("My dog's name is", x) In this case x is not a very good name for a variable. A better name would be: name fmt.PrintIn("My dog's name is", name) or even: dogsName := "Max" fmt.PrintIn("My dog's name is", dogsName) In this last case we use a special way to represent mul- tiple words in a variable name known as lower camel case (also know as mixed case, bumpy caps, camel back or hump back). The first letter of the first word is lowercase, the first letter of the subsequent words is uppercase and all the other letters are lowercase. 4.2 Scope Going back to the program we saw at the beginning of 4 Variables the chapter: package main import “fart func main() { var x string fit .Print1n(x) Another way of writing this program would be like this: package main import “fart var x string = "Hello World” func main() { ‘fmt. Print1n(x) + Notice that we moved the variable outside of the main function. This means that other functions can access this variable: Variables 42 var x string = "Hello World" func main() { fmt. Printin(x) + func #() { fmt. Print1n(x) + ‘The f function now has access to the x variable. Now suppose that we wrote this instead: func main() { var x string = "Hello World” fmt. Print1n(x) + func £() { fmt. Printin(x) + If you run this program you should see an error: «\main..go: undefined: x ‘The compiler is telling you that the x variable inside of the f function doesn't exist. It only exists inside of the main function. The range of places where you are al- lowed to use x is called the scope of the variable. Ac- 43 Variables cording to the language specification “Go is lexically scoped using blocks”. Basically this means that the variable exists within the nearest curly braces { } (a block) including any nested curly braces (blocks), but not outside of them. Scope can be a little confusing at first; as we see more Go examples it should become more clear. 4.3 Constants Go also has support for constants. Constants are basi- cally variables whose values cannot be changed later. ‘They are created in the same way you create variables but instead of using the var keyword we use the const keyword: package main import “fart func main() { const x string = "Hello World" fmt. Println(x) This: Variables 4 const x string = "Hello World” x = "Some other string” Results in a compile-time error: +\main.go:7: cannot assign to x Constants are a good way to reuse common values in a program without writing them out each time. For ex- ample Pi in the math package is defined as a constant. 4.4 Defining Multiple Variables Go also has another shorthand when you need to de- fine multiple variables: ‘Use the keyword var (or const) followed by parenthe- ses with each variable on its own line. 45 Variables 4.5 An Example Program Here's an example program which takes in a number entered by the user and doubles it: package main import “fart func main() { fmt.Print("Enter a number: ") var input floated fmt.Scanf("%F", &input) output input * 2 fmt .Print1n(output) We use another function from the ft package to read the user input (Scanf). &input will be explained in a later chapter, for now all we need to know is that Scant fills input with the number we enter. Variables 16 Problems 1. What are two ways to create a new variable? 2. What is the value of x after running: x i= 53 x41? 3. What is scope and how do you determine the scope of a variable in Go? 4, What is the difference between var and const? 5. Using the example program as a starting point, write a program that converts from Fahrenheit into Celsius. (¢ = (F - 32) * 5/9) 6. Write another program that converts from feet into meters. (1 ft = @.3048 m) 5 Control Structures Now that we know how to use variables it's time to start writing some useful programs. First let's write a program that counts to 10, starting from 1, with each number on its own line. Using what we've learned so far we could write this: package main import "fart func main() { fmt Print1n(1) fmt .Print1n(2) fmt.Print1n(3) fmt. Print1n(4) fmt.Print1n(5) fmt .Print1n(6) fmt. Print1n(7) fmt Print1n(8) fmt.Print1n(9) fmt. Print1n(10) Or this: a7 Control Structures 48 package main import "fmt" func main() { fmt.PrintIn(*4 But both of these programs are pretty tedious to write, What we need is a way of doing something multiple times. 5.1 For The for statement allows us to repeat a list of state- ments (a block) multiple times. Rewriting our previous program using a for statement looks like this: 49 Control Structures package main import “fmt” func main() { died for i <= 10 { fmt. PrintIn(i) ita First we create a variable called i that we use to store the number we want to print. Then we create a for loop by using the keyword for, providing a conditional expression which is either true or false and finally supplying a block to execute. The for loop works like this: 1. We evaluate (run) the expression i <= 10 (“i less than or equal to 10"). If this evaluates to true then we run the statements inside of the block, Otherwise we jump to the next line of our pro- gram after the block, (in this case there is noth ing after the for loop so we exit the program) 2, After we run the statements inside of the block we loop back to the beginning of the for state- ment and repeat step 1. Control Structures 50 The i = i + 1 line is extremely important, because without it i <= 1@ would always evaluate to true and our program would never stop. (When this happens this is referred to as an infinite loop) ‘As an exercise lets walk through the program like a computer would: + Create a variable named i with the value 1 + Is i <= 10? Yes. + Print i + Set ito i + 1 (i now equals 2) + Isi <= 10? Yes. + Print i + Set ito i + 1 (i now equals 3) + Set i toi + 1 (i now equals 11) + Is i <= 10? No. + Nothing left to do, so exit Other programming languages have a lot of different types of loops (while, do, until, foreach, ...) but Go only has one that can be used in a variety of different ways. The previous program could also have been written like this: 51 Control Structures func main() { for i := 1; i <= 10; itt { fmt. Printin(i) + Now the conditional expression also contains two other statements with semicolons between them. First we have the variable initialization, then we have the con- dition to check each time and finally we “increment” the variable. (adding 1 to a variable is so common that we have a special operator: ++. Similarly subtracting 1 can be done with --) We will see additional ways of using the for loop in later chapters. 5.2 If Let's modify the program we just wrote so that instead of just printing the numbers 1-10 on each line it also specifies whether or not the number is even or odd. Like this: Control Structures 52 First we need a way of determining whether or not a number is even or odd. An easy way to tell is to divide the number by 2. If you have nothing left over then the number is even, otherwise it's odd. So how do we find the remainder after division in Go? We use the % oper- ator. 1 % 2 equals 1,2 % 2 equals 0, 3 % 2 equals 1 and s0 on. Next we need a way of choosing to do different things based on a condition. For that we use the if state- ment: An if statement is similar to a for statement in that it 58 Control Structures has a condition followed by a block. If statements also have an optional else part. If the condition evaluates to true then the block after the condition is run, other- wise either the block is skipped or if the else block is present that block is run. If statements can also have else if parts: UFiK2 == 0 // divisible by 2 } else if 1% 3 == 0 { // divisible by 3 }else if ix4--0{ // divisible by 4 d ‘The conditions are checked top down and the first one to result in true will have its associated block exe- cuted, None of the other blocks will execute, even if their conditions also pass. (So for example the number 8 is divisible by both 4 and 2, but the // divisible by 4 block will never execute because the // divisible by 2 block is done first) Putting it all together we have: Control Structures 54 func main() { fori i= a; 4 if iK2 fmt.PrintIn(i, “even") } else { fmt.PrintIn(i, “odd") Let's walk through this program: + Create a variable i of type int and give it the value 1 + Is i less than or equal to 16? Yes: jump to the block + Is the remainder of i + 2 equal to 6? No: jump to the else block + Print i followed by odd + Increment i (the statement after the condition) + Is i less than or equal to 10? Yes: jump to the block + Is the remainder of i + 2 equal to 8? Yes: jump to the if block + Print i followed by even The remainder operator, while rarely seen outside of elementary school, turns out to be really useful when programming. You'll see it turn up everywhere from zebra s riping tables to partitioning data sets 56 Control Structures 5.3 Switch Suppose we wanted to write a program that printed the English names for numbers. Using what we've learned so far we might start by doing this: if isso fmt. Print1n("Zero") }else if i { fmt.Print1n("One") } else if i == 2{ fmt.Print1n("Two") } else if i fmt. Print1n("Three") } else if i == 4{ fmt. Print1n("Four") } else if i == 5 { fmt.Print1n("Five") + Since writing a program in this way would be pretty tedious Go provides another statement to make this easier: the switch statement. We can rewrite our pro- gram to look like this: Control Structures 56 switch i { case 0: fmt.PrintIn("Zero") case 1: fmt.Print1n("One") case 2: fmt.PrintIn("Two") case 3: fmt.Print1n("Three") case 4: fmt.Print1n("Four") case 5: fmt.Print1n("Five") default: fmt.Print1n("Unknown Number") + A switch statement starts with the keyword switch fol- lowed by an expression (in this case i) and then a se- ries of cases. The value of the expression is compared to the expression following each case keyword. If they are equivalent then the statement(s) following the : is executed. Like an if statement each case is checked top down. and the first one to succeed is chosen. A switch also supports a default case which will happen if none of the cases matches the value. (Kind of like the else in an if statement) These are the main control flow statements. Additional statements will be explored in later chapters. 87 Control Structures Problems 1. What does the following program print: i:=10 if i > 10 { fmt. Println("Big") } else { fmt. Print1n("Smal1") + 2. Write a program that prints out all the numbers evenly divisible by 3 between 1 and 100. (3, 6, 9, etc.) 3, Write a program that prints the numbers from 1 to 100, But for multiples of three print "Fizz" in- stead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". 6 Arrays, Slices and Maps In chapter 3 we learned about Go's basic types. In this chapter we will look at three more built-in types: ar- rays, slices and maps. 6.1 Arrays An array is a numbered sequence of elements of a sin- gle type with a fixed length. In Go they look like this: var x [S]int x is an example of an array which is composed of 5 ints. Try running the following program: 59 Arrays, Slices and Maps package main import “fmt func main() { var x [S]int x[4] = 100 fmt. Print1n(x) You should see this: [eo @ @ @ 100] x[4] = 100 should be read “set the 5 element of the array x to 100”. It might seem strange that x[4] repre- sents the 5" element instead of the 4" but like strings, arrays are indexed starting from 0, Arrays are ac- cessed in a similar way. We could change fmt .Print1n(x) to fmt.PrintIn(x[4]) and we would get 100. Here's an example program that uses arrays: Arrays, Slices and Maps 60 func main() { var x [S]floates x[@] = 98 x[1] = 93 x[2] = 77 x[3] = 82 x(4] = 83 var total floated = @ for i i= 0; i < 53 it { total += x[i] + fmt.Printin(total / 5) This program computes the average of a series of test scores. If you run it you should see 86.6. Let's walk through the program: + First we create an array of length 5 to hold our test scores, then we fill up each element with a grade + Next we setup a for loop to compute the total score + Finally we divide the total score by the number of el- ements to find the average This program works, but Go provides some features we can use to improve it. First these 2 parts; i < 5 and total / 5 should throw up a red flag for us, Say we 61 Arrays, Slices and Maps changed the number of grades from 5 to 6. We would also need to change both of these parts. It would be better to use the length of the array instead: var total floatea = @ for i z= 0; i < len(x); itt { total += x[i] } fmt.Printin(total / len(x)) Go ahead and make these changes and run the pro- gram. You should get an error: $ go run tmp.go # command-1ine-arguments «\tmp.go:19: invalid operation: total / 5 (mismatched types floate4 and int) The issue here is that len(x) and total have different types, total is a float64 while Len(x) is an int. So we need to convert 1en(x) into a float64: fnt.PrintIn(total / floate4(len(x))) ‘This is an example of a type conversion. In general to convert between types you use the type name like a function. Arrays, Slices and Maps 62 Another change to the program we can make is to use a special form of the for loop: var total floated = 0 for i, value := range x { total += value + fmt.PrintIn(total / floate4(1en(x))) In this for loop i represents the current position in the array and value is the same as x[i]. We use the key- word range followed by the name of the variable we want to loop over. Running this program will result in another error: $ go run tmp.go # command-1ine-arguments «\tmp.go:16: i declared and not used The Go compiler won't allow you to create variables that you never use. Since we don't use i inside of our loop we need to change it to this: 68 Arrays, Slices and Maps var total floated = 0 for _, value := range x { total += value y fmt.PrintIn(total / float64(len(x))) A single _ (underscore) is used to tell the compiler that we don't need this. (In this case we don't need the iter- ator variable) Go also provides a shorter syntax for creating arrays: [S]floatea{ 98, 93, 77, 82, 83 } We no longer need to specify the type because Go can figure it out. Sometimes arrays like this can get too long to fit on one line, so Go allows you to break it up like this: [S]floatea{ 98, 93, 77, 82, 83, Notice the extra trailing , after 83. This is required by Arrays, Slices and Maps 64 Go and it allows us to easily remove an element from the array by commenting out the line: [4] floatea{ 98, 93, 7, 82, 11 83, This example illustrates a major issue with arrays: their length is fixed and part of the array's type name. In order to remove the last it em, we actually had to change the type as well. Go's solution to this problem is to use a different type: slices. 6.2 Slices Aslice is a segment of an array. Like arrays slices are indexable and have a length. Unlike arrays this length is allowed to change. Here's an example of a slice: var x []floates The only difference between this and an array is the missing length between the brackets. In this case x has been created with a length of @. 65 Arrays, Slices and Maps If you want to create a slice you should use the built-in make function: x t= make([]float64, 5) ‘This creates a slice that is associated with an underly- ing floated array of length 5. Slices are always associ- ated with some array, and although they can never be longer than the array, they can be smaller. The make function also allows a 3" parameter: x := make([]floate4, 5, 10) 10 represents the capacity of the underlying array which the slice points to: x Another way to create slices is to use the [low : high] expression: arr = [S]}floatea{1,2,3,4,5} x t= arr[@:5] Arrays, Slices and Maps 66 low is the index of where to start the slice and high is the index where to end it (but not including the index itself). For example while arr[@:5] returns [1,2,3,4,5], arr[1:4] returns [2,3,4] For convenience we are also allowed to omit low, high or even both low and high. arr[@:] is the same as arr[@:len(arr)], arr[:5] is the same as arr[@:5] and arr[:] is the same as arr[@:len(arr)]. Slice Functions Go includes two built-in functions to assist with slices: append and copy. Here is an example of append: func main() { slicel := [Jint(1,2,3) slice2 := append(slice1, 4, 5) fmt.PrintIn(slicel, slice2) After running this program slice has [1,2,3] and slice2 has [1,2,3,4,5]. append creates a new slice by taking an existing slice (the first argument) and ap- pending all the following arguments to it. Here is an example of copy: func main() { slicel := [Jint(1,2,3} slice2 := make([]int, 2) copy(slice2, slice1) fmt.PrintIn(slicel, slice2) After running this program slice1 has [1,2,3] and slice2 has [1,2]. The contents of slice1 are copied into slice2, but since slice? has room for only two ele- ments only the first two elements of slice are copied. 6.3 Maps A map is an unordered collection of key-value pairs. Also known as an associative array, a hash table or a dictionary, maps are used to look up a value by its as- sociated key. Here's an example of a map in Go: var x map[string]int ‘The map type is represented by the keyword map, fol- lowed by the key type in brackets and finally the value type. If you were to read this out loud you would say “x is a map of strings to ints.” Like arrays and slices maps can be accessed using brackets. Try running the following program: Arrays, Slices and Maps 68 var x map[string]int x["key"] = 10 fmt. Printin(x) ‘You should see an error similar to this: panic: runtime error: assignment to entry in nil map goroutine 1 [running]: main.main() main.go:7 +0x4d goroutine 2 [syscall]: created by runtime.main C:/Users/ADMINI~1/AppData/Local/Temp/2/bindi 269497170/go/src/pkg/runtime/proc.c:221 exit status 2 Up till now we have only seen compile-time errors. This is an example of a runtime error. As the name would imply, runtime errors happen when you run the program, while compile-time errors happen when you try to compile the program. The problem with our program is that maps have to be initialized before they can be used. We should have written this: make(map[string] int) x["key"] = 10 Fmt .Print1n(x["key"]) If you run this program you should see 1@ displayed. ‘The statement x["key"] = 10 is similar to what we saw with arrays but the key, instead of being an inte- ger, is a string because the map's key type is string. We can also create maps with a key type of int: make(map[int]int) x[1] = 10 nt. PrintIn(x[1]) ‘This looks very much like an array but there are a few differences, First the length of a map (found by doing 1en(x)) can change as we add new items to it. When first created it has a length of 0, after x[1] = 10 it has a length of 1. Second maps are not sequential. We have x{1], and with an array that would imply there must be an x[@], but maps don't have this requirement. We can also delete items from a map using the built-in delete function: delete(x, 1) Arrays, Slices and Maps 70 Let's look at an example program that uses a map: package main import "fmt" func main() { elements := make(map[string]string) elements["H"] = “Hydrogen” elements[ elements[ = "Lithium" elements["Be"] = "Beryllium" elements["B"] = "Boron" elements["C"] = "Carbon" elements["N"] = “Nitrogen” elements["0"] = “Oxygen” elements["F"] = "Fluorine" elements["Ne"] = "Neon" fmt Print1n(elements["Li"]) elenents is a map that represents the first 10 chemical elements indexed by their symbol. This is a very com- mon way of using maps: as a lookup table or a dictio- nary. Suppose we tried to look up an element that doesn't exist: fmt. Printin(elements["Un"]) If you run this you should see nothing returned. Tech- a Arrays, Slices and Maps nically a map returns the zero value for the value type (which for strings is the empty string). Although we could check for the zero value in a condition (elenents[“Un"] == "*) Go provides a better way: name, ok := elements["Un"] fnt.PrintIn(name, ok) Accessing an element of a map can return two values instead of just one. The first value is the result of the lookup, the second tells us whether or not the lookup was successful. In Go we often see code like this: if name, ok := elements[ fmt.PrintIn(name, ok) + First we try to get the value from the map, then if it's suecessful we run the code inside of the block. Like we saw with arrays there is also a shorter way to create maps: Arrays, Slices and Maps 72 map[string]string{ “Hydrogen”, : "Helium", “Lithium “Beryllium”, Boron”, "carbon", “Nitrogen”, “Oxygen”, Fluorine”, : "Neon", elements Maps are also often used to store general information. Let's modify our program so that instead of just stor- ing the name of the element we store its standard state (state at room temperature) as well: func main() { elements := map[string]map[string]string{ “H": map[string]string{ Heliu "state": "gas", map[string]string( "name" :"Lithium”, b + if el, ok := elements["Li"]; ok { fmt.PrintIn(el["name"], el["state"]) + Arrays, Slices and Maps "Be": map[string]string{ Beryllium", map[string]string{ "name": "Carbon", 9 Olid”, map[string]string{ "name": "Nitrogen", “state "name F “state” map[string]string{ "name" :"Fluorine”, "Ne": map[string]string( "name" :"Neon", "state": "gas", Notice that the type of our map has changed from Arrays, Slices and Maps 4 map[string]string to map[string]map[string]string ‘We now have a map of strings to maps of strings to strings. The outer map is used as a lookup table based on the element's symbol, while the inner maps are used to store general information about the elements. Although maps are often used like this, in chapter 9 we will see a better way to store structured informa- tion, 5 Arrays, Slices and Maps Problems 1. How do you access the 4" element of an array or slice? 2. What is the length of a slice created using: make([Jint, 3, 9)? 3. Given the array: [6]stringt what would x[2:5] give you? 4, Write a program that finds the smallest number in this list: r= []int¢ 48,96, 86,68, 57,82, 63,70, 37,34, 83,27, 19,97, 9,17, 7 Functions A function is an independent section of code that maps zero or more input parameters to zero or more output parameters. Functions (also known as procedures or subroutines) are often represented as a black box: (the black box represents the function) =~ | ao Until now the programs we have written in Go have used only one function: func main() {} We will now begin writing programs that use more than one function. 76 7 Functions 7.1 Your Second Function Remember this program from chapter 6: func main() { xs := []float64(98,93,77,82,83} total := 0.8 for _, v := range xs { total += v + fmt.PrintIn(total / float64(1en(xs))) ‘This program computes the average of a series of num- bers. Finding the average like this is a very general problem, so its an ideal candidate for definition as a function. ‘The average function will need to take in a slice of float64s and return one float64. Insert this before the main function: func average(xs []float64) floates { panic("Not Implemented”) + Functions start with the keyword func, followed by the function's name. The parameters (inputs) of the func- Functions 78 tion are defined like this: name type, name type, .. Our function has one parameter (the list of scores) that we named xs. After the parameters we put the return type. Collectively the parameters and the return are known as the function's signature. Finally we have the function body which is a series of statements between curly braces. In this body we in- voke a built-in function called panic which causes a run time error. (We'll see more about panic later in this chapter) Writing functions can be difficult so it's a good idea to break the process into manageable chunks, rather than trying to implement the entire thing in one large step. Now lets take the code from our main function and move it into our average function: func average(xs []floatea) floatea { total := 0.@ for _, v := range xs { total += v + return total / float64(len(xs)) Notice that we changed the fmt.Println to be a return instead. The return statement causes the function to immediately stop and return the value after it to the 79 Functions function that called this one. Modify main to look like this: func main() { xs t= []floate4{98,93,77,82,83} nt. Print1n(average(xs)) Running this program should give you exactly the same result as the original. A few things to keep in mind: + The names of the parameters don't have to match in the calling function. For example we could have done func main() { someOtherName := []float64{98,93,77,82,83} fmt .Print1n(average(someOtherName) ) And our program would still work. + Functions don’t have access to anything in the call- ing function. This won't work: Functions 80 func #() { mit. Print1n(x) + func main() { xisS FO We need to either do this: func #(x int) { fmt. Print1n(x) + func main() { XinS F(x) Or this: var x int = func #() { fit Print1n(x) + func main() { #Q + Functions are built up in a “stack”. Suppose we had this program: 81 Functions func main() { fmt .Println(f1()) + func £1() int { return 2() ? func £2() int { return 1 + We could visualize it like this: return a lao 4a return Tam] #0 fae main main ain Each time we call a function we push it onto the call stack and each time we return from a function we pop the last function off of the stack. + We can also name the return type: func £2() (r int) { rei return Functions 82 7.2 Returning Multiple Values Go is also capable of returning multiple values from a funtion: func #() (int, int) { return 5, 6 + func main() { % y t= #0) ‘Three changes are necessary: change the return type to contain multiple types separated by ,, change the expression after the return so that it contains multiple expressions separated by , and finally change the as- signment statement so that multiple values are on the left side of the : or =, ‘Multiple values are often used to return an error value along with the result (x, err := £()), or a boolean to indicate success (x, ok i= ()) 7.3. Variadic Functions There is a special form available for the last parameter in a Go function: 83 Functions func add(args ...int) int { range args { return total + func main() { fmt.PrintIn(add(1,2,3)) + By using ... before the type name of the last parame- ter you can indicate that it takes zero or more of those We invoke the function like any other function except we parameters. In this case we take zero or more in can pass as many ints as we want. ‘This is precisely how the fmt.PrintIn function is im- plemented: func Printin(a ... error) ‘The Printin function takes any number of values of any type. (The special interface{} type will be dis- cussed in more detail in chapter 9) We can also pass a slice of ints by following the slice with . Functions 84 func main() { xs := [Jint(1,2,3} fmt. PrintIn(add(xs...)) 7.4 Closure It is possible to create functions inside of functions: func main() { add := func(x, y int) int { return x + y mt. Print1n(add(1,1)) add is a local variable that has the type func(int, int) int (a function that takes two ints and returns an int). When you create a local function like this it also has access to other local variables (remember scope from chapter 4): 85 Functions func main() { xi=@ increment := func() int { Xe return x + mt Print1n(increment()) fmt .Print1n(increment()) increment adds 1 to the variable x which is defined in the main function's scope. This x variable can be ac- cessed and modified by the increment function. This is why the first time we call increment we see 1 dis- played, but the second time we call it we see 2 di played. A function like this together with the non-local vari- ables it references is known as a closure. In this case increment and the variable x form the closure. One way to use closure is by writing a function which returns another function which — when called — can generate a sequence of numbers. For example here's how we might generate all the even numbers: Functions 86 func makeEvenGenerator() func() uint { i t= uint(@) return func() (ret uint) { ret =i its2 return + + func main() { nextEven := makeEvenGenerator() ft PrintIn(nextéven()) // @ fmt.PrintIn(nextéven()) // 2 fmnt.PrintIn(nextéven()) // 4 makeEvenGenerator returns a function which generates even numbers. Each time it's called it adds 2 to the lo- cal i variable which — unlike normal local variables — persists between calls. 75 Recursion Finally a function is able to call itself. Here is one way to compute the factorial of a number: 87 Functions func factorial (x uint) uint { if x == 0 { return 1 } return x * factorial(x-1) factorial calls itself, which is what makes this func- tion recursive. In order to better understand how this function works, lets walk through factorial(2): + Isx == @? No. (xis 2) + Find the factorial of x = 1 + Isx == @? No, (xis 1) + Find the factorial of x - 1 + Isx @? Yes, return 1. + return #1 + return 2 #1 Closure and recursion are powerful programming tech- niques which form the basis of a paradigm known as functional programming. Most people will find fune- tional programming more difficult to understand than an approach based on for loops, if statements, vari- ables and simple functions. Functions 88 7.6 Defer, Panic & Recover Go has a special statement called defer which sched- ules a function call to be run after the function com- pletes. Consider the following example: package main import "fmt" func first() { fmt .Print1n("1st") + func second() { nt .Print1n("2nd") y func main() { defer second() first() This program prints 1st followed by 2nd. Basically de- fer moves the call to second to the end of the function: func main() { first() second() defer is often used when resources need to be freed in some way. For example when we open a file we need to 89 Functions make sure to close it later. With defer: f, . os.Open(filename) defer f ‘lose() ‘This has 3 advantages: (1) it keeps our Close call near our Open calll so its easier to understand, (2) if our fune- tion had multiple return statements (perhaps one in an if and one in an else) Close will happen before both of them and (3) deferred functions are run even if a run-time panic occurs. Panic & Recover Earlier we created a function that called the panic function to cause a run time error, We can handle a run-time panic with the built-in recover function. recover stops the panic and returns the value that was passed to the calll to panic. We might be tempted to use it like this: Functions 90 package main import “Fmt™ func main() { panic("PANIC") str := recover() fnt.Print1n(str) But the call to recover will never happen in this case because the call to panic immediately stops execution of the function. Instead we have to pair it with defer: package main import "fmt" func main() { defer func() { str := recover() fmt.Println(str) 10, panic( “PANIC A panic generally indicates a programmer error (for example attempting to access an index of an array that's out of bounds, forgetting to initialize a map, ete.) or an exceptional condition that there's no easy way to recover from, (Hence the name “panic”) a Functions Problems . sum is a function which takes a slice of numbers and adds them together. What would its func- tion signature look like in Go? Write a function which takes an integer and halves it and returns true if it was even or false if it was odd. For example half(1) should return (®, false) and half(2) should return (1, true). Write a function with one variadic parameter that finds the greatest number in a list of num- bers. Using makeEvenGenerator as an example, write a makeOddGenerator function that generates odd numbers. ‘The Fibonacci sequence is defined as: #ib(@) = @, #ib(1) = 1, Fib(n) = fib(n-2) + #ib(n-2). Write a recursive function which can find Fib(n) What are defer, panic and recover? How do you recover from a run-time panic? 8 Pointers When we call a function that takes an argument, that, argument is copied to the function: func zero(x int) { x=@ + func main() { xie5 zero(x) fmt.PrintIn(x) // x is still 5 In this program the zero function will not modify the original x variable in the main function. But what if we wanted to? One way to do this is to use a special data type known as a pointer: 92 98 Pointers func zero(xPtr *int) { =xptr = @ + func main() { Xim5 zero(&x) fmt .Println(x) // x is @ Pointers reference a location in memory where a value is stored rather than the value itself. (hey point to something else) By using a pointer (*int) the zero function is able to modify the original variable. 8.1 The * and & operators In Go a pointer is represented using the * (asterisk) character followed by the type of the stored value. In the zero function xPtr is a pointer to an int. * is also used to “dereference” pointer variables. Deref- erencing a pointer gives us access to the value the pointer points to. When we write *xPtr = @ we are say- ing “store the int 0 in the memory location xPtr refers to”. If we try xPtr = @ instead we will get a compiler error because xPtr is not an int it's a *int, which can only be given another *int. Finally we use the & operator to find the address of a Pointers 4 variable, &x returns a *int (pointer to an int) because x is an int. This is what allows us to modify the original variable, &x in main and xPtr in zero refer to the same memory location. 8.2 new Another way to get a pointer is to use the built-in new function: func one(xPtr *int) { *xptr = 1 + func main() { xPtr i= new(int) one(xPtr) fnt.PrintIn(*xPtr) // x is 1 new takes a type as an argument, allocates enough memory to fit a value of that type and returns a pointer to it. In some programming languages there is a significant, difference between using new and &, with great care be- ing needed to eventually delete anything created with new. Go is not like this, it's a garbage collected pro- gramming language which means memory is cleaned up automatically when nothing refers to it anymore. 95 Pointers Pointers are rarely used with Go's built-in types, but as we will see in the next chapter, they are extremely useful when paired with structs. Pointers 96 Problems 1. How do you get the memory address of a vari- able? 2. How do you assign a value to a pointer? 3. How do you create a new pointer? 4, What is the value of x after running this pro- gram: func square(x *float64) { ye KH HK + func main() { x i= 1,5 square(&x) 5. Write a program that can swap two integers (x := 45 y t= 25 swap(&x, &y) should give you x=2 and y=1), 9 Structs and Interfaces Although it would be possible for us to write programs only using Go's built-in data types, at some point it would become quite tedious. Consider a program that interacts with shapes: package main import (“fmt"; “math") func distance(x1, y1, x2, y2 floatea) floatea { a t= x2 - x1 brs y2- yl return math.Sqrt(ata + b*b) + func rectangleérea(xi, yl, x2, y2 float64) floatea { 1 t= distance(x1, y1, x1, y2) w i= distance(x1, y1, x2, y1) return 1 * w } func circleArea(x, y, r float64) floated { return math.Pi * r¥r > Structs and Interfaces 98 func main() { var rxi, ry1 floated = 0, @ var rx2, ry2 floates = 18, 10 var cx, cy, cr floated = 0, @, 5 fnt.PrintIn(rectangledrea(rx1, ry1, rx2, ry2)) fmt .PrintIn(circleArea(cx, cy, cr)) + Keeping track of all the coordinates makes it difficult to see what the program is doing and will likely lead to mistakes. 91 Structs ‘An easy way to make this program better is to use a struct. A struct is a type which contains named fields. For example we could represent a Cirele like this: type Circle struct { x floatea y floatea Pr floated The type keyword introduces a new type. It's followed by the name of the type (Circle), the keyword struct to indicate that we are defining a struct type and a list of fields inside of curly braces. Each field has a 99 Structs and Interfaces name and a type. Like with functions we can collapse fields that have the same type: type Circle struct { x, ys P floates + Initialization We can create an instance of our new Circle type in a variety of ways: var ¢ Circle Like with other data types, this will create a local Cir- cle variable that is by default set to zero. For a struct zero means each of the fields is set to their correspond- ing zero value @ for ints, 0.0 for floats, “" for strings, nil for pointers, ...) We can also use the new function: new(Circle) This allocates memory for alll the fields, sets each of them to their zero value and returns a pointer. (#Circle) More often we want to give each of the fields a value, We can do this in two ways. Like this: Structs and Interfaces 100 Circle(x: @, y: @, r: 5} Or we can leave off the field names if we know the or- der they were defined: c r= Circle{@, @, 5} Fields We can access fields using the . operator: fmt.PrintIn(c.x, c.y, ¢.r) cx = 10 cy Let's modify the circleArea function so that it uses a Circle: func circlearea(c Circle) floatea { return math.Pi * c.r*c.r + In main we have: ¢ t= Circle{e, @, 5} fmt. Print1n(circlearea(c)) 101 Structs and Interfaces One thing to remember is that arguments are always copied in Go. If we attempted to modify one of the fields inside of the circleArea function, it would not modify the original variable. Because of this we would typically write the function like this: func circleArea(c *Circle) float64 { return math.Pi * c.r*c.r + ‘And change main: ¢ r= Circle{o, @, 5} nt Print1n(circlearea(&c)) 9.2. Methods Although this is better than the first version of this code, we can improve it significantly by using a special type of function known as a method: func (c *Circle) area() floatea { return math.Pi * c.r¥c.r + In between the keyword func and the name of the function we've added a “receiver”. The receiver is like a Structs and Interfaces 102 parameter — it has a name and a type — but by creating the function in this way it allows us to call the function using the . operator: fmt.Print1n(c.area()) This is much easier to read, we no longer need the & operator (Go automatically knows to pass a pointer to the circle for this method) and because this function can only be used with Circles we can rename the func- tion to just area. Let's do the same thing for the rectangle: type Rectangle struct { x1, yl, x2, y2 floates + func (r *Rectangle) area() floates { 1 i= distance(r.x1, rayl, r.x1, r-y2) w i= distance(r.x1, r.y1, F.x2, r-y1) return 1 * w main has: t= Rectangle(@, @, 10, 16) fmt.Printin(r.area()) 108 Structs and Interfaces Embedded Types A struct’s fields usually represent the has-a relation- ship. For example a Circle has a radius. Suppose we had a person struct: type Person struct { Name string + func (p *Person) Talk() { fimt.Print1n("Hi, my name is", p.Name) + And we wanted to create a new Android struct. We could do this: type Android struct { Person Person Model string This would work, but we would rather say an Android is a Person, rather than an Android has a Person. Go supports relationships like this by using an embedded type. Also known as anonymous fields, embedded types look like this: Structs and Interfaces 104 type Android struct { Person Model string We use the type (Person) and don't give it a name. When defined this way the Person struct can be ac- cessed using the type name: a := new(Android) a.Person.Talk() But we can also call any Person methods directly on the Android: a := new(Android) a.Talk() ‘The is-a relationship works this way intuitively: Peo- ple can talk, an android is a person, therefore an an- droid can talk. 9.3 Interfaces You may have noticed that we were able to name the Rectangle's area method the same thing as the Circle's area method. This was no accident. In both real life 105 Structs and Interfaces and in programming, relationships like these are com- monplace. Go has a way of making these accidental similarities explicit through a type known as an Inter- face. Here is an example of a Shape interface: type Shape interface { area() floatea + Like a struct an interface is created using the type keyword, followed by a name and the keyword interface. But instead of defining fields, we define a “method set”. A method set is a list of methods that a type must have in order to “implement” the interface. In our case both Rectangle and Circle have area meth- ods which return float64s so both types implement the Shape interface. By itself this wouldn't be particularly useful, but we can use interface types as arguments to functions: func totalArea(shapes ...Shape) floates { var area float64 for _, 5 := range shapes { ‘area += s.area() + return area Structs and Interfaces 106 ‘We would call this function like this: fmt.Printin(totalArea(&c, &r)) Interfaces can also be used as fields: type Multishape struct { shapes []Shape + ‘We can even turn MultiShape itself into a Shape by giv- ing it an area method: func (m *MultiShape) area() floate4 { var area floated for _, s := range m.shapes { area += s.area() + return area Now a MultiShape can contain Circles, Rectangles or even other MultiShapes,

You might also like