28,99 €
Tackle GoLang with practical and employment-focused instruction
In Job Ready Go, software education guru Dr. Haythem Balti delivers an essential and hands-on guide to Go, an open-source programming language developed by Google engineers to combine the most sought-after capabilities of other programming languages, including Java, C#, and C++. In the book, the author walks you through all the most critical skills necessary for successful, on-the-job Go programming.
You’ll discover:
Job Ready Go offers readers straightforward and elegant instruction based on the renowned mthree Global Academy and Software Guild training program. It’s an essential read for aspiring Go developers looking for a fast-track to developing real-world skills demanded by employers.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 753
Veröffentlichungsjahr: 2022
Cover
Title Page
Introduction
WHAT DOES THIS BOOK COVER?
READER SUPPORT FOR THIS BOOK
PART I: The Basics of the Go Programming Language
Lesson 1: Getting Started with Go
INSTALLING GO
TESTING THE INSTALLATION
CREATING A HELLO, WORLD! PROGRAM
MULTIPLE VERSIONS OF GO
ONLINE EDITOR FOR GO: THE GO PLAYGROUND
SUMMARY
EXERCISES
Lesson 2: Understanding Go Basics
UNDERSTANDING STATEMENTS AND TOKENS
STATEMENTS
COMMENTS
IDENTIFIERS
KEYWORDS
SUMMARY
EXERCISES
Lesson 3: Storing with Variables
VARIABLES
STATIC VS. DYNAMIC TYPE DECLARATION
VARIABLE SCOPE
OBTAINING USER INPUT
CONVERTING A STRING TO A NUMBER
NUMERIC DATA TYPES
SUMMARY
EXERCISES
Lesson 4: Performing Operations
ARITHMETIC OPERATIONS
ASSIGNMENT OPERATIONS
WORKING WITH BOOLEANS
RELATIONAL OPERATIONS
BOOLEAN OPERATIONS
MATH FUNCTIONS
BITWISE OPERATIONS
RANDOM NUMBERS
SUMMARY
EXERCISES
Lesson 5: Controlling Program Flow with Conditional Statements
CONDITIONAL STATEMENTS
USING AN
IF
STATEMENT
WORKING WITH MULTIPLE CONDITIONS
USING AN
IF-ELSE
STATEMENT
CREATING NESTED
IF
STATEMENTS
USING A
SWITCH
STATEMENT
SUMMARY
EXERCISES
Lesson 6: Controlling Program Flow with Loops
LOOPING STATEMENTS
FOR
LOOPS
LOOPING THROUGH A STRING
THE
RANGE
FUNCTION
LOOP CONTROL STATEMENTS
SUMMARY
EXERCISES
Lesson 7: Pulling It All Together: Income Tax Calculator
GETTING STARTED
STEP 1: GATHER REQUIREMENTS
STEP 2: DESIGN THE PROGRAM
STEP 3: CREATE THE INPUTS
STEP 4: CALCULATE THE TAXABLE INCOME
STEP 5: CALCULATE THE TAX RATE
STEP 6: UPDATE THE APPLICATION
STEP 7: ADDRESS THE UI
ON YOUR OWN
SUMMARY
PART II: Organizing Code and Data in Go
Lesson 8: Using Functions
DEFINING A FUNCTION
VARIADIC FUNCTIONS
RECURSION
FUNCTION AS A VALUE
CLOSURES
SUMMARY
EXERCISES
Lesson 9: Accessing Arrays
DECLARING AN ARRAY
DECLARING AND INITIALIZING AN ARRAY
INFERRING ARRAY SIZE
USING A
FOR
LOOP TO DEFINE AN ARRAY
USING RANGE WITH AN ARRAY
CREATING MULTIDIMENSIONAL ARRAYS
DUPLICATING AN ARRAY
COMPARING ARRAYS
SUMMARY
EXERCISES
Lesson 10: Working with Pointers
CREATING A POINTER
ACCESSING THE STORED VALUE OF A POINTER
UNDERSTANDING
NIL
POINTERS
USING POINTERS TO CHANGE VARIABLES
COMPARING POINTERS
WORKING WITH AN ARRAY OF POINTERS
USING POINTERS WITH FUNCTIONS
SUMMARY
EXERCISES
Lesson 11: Organizing with Structs
DECLARING AND INITIALIZING A STRUCT
USING KEY-VALUE PAIRS WITH STRUCTS
USING THE
NEW
KEYWORD
POINTERS AND STRUCTS
NESTED STRUCTS
ADDING METHODS TO A STRUCT
TYPE AND VALUE
COMPARING STRUCTS
SUMMARY
EXERCISES
Lesson 12: Accessing Slices
HOW SLICES WORK
SLICE AN ARRAY
CHANGING THE SIZE OF A SLICE
ITERATING THROUGH A SLICE
THE
MAKE
FUNCTION
CREATING A SLICE VARIABLE WITH
VAR
WORKING WITH SLICE ELEMENTS
APPENDING TO A SLICE USING THE
APPEND
FUNCTION
COPYING A SLICE
CREATING A SLICE USING THE
NEW
KEYWORD
REMOVING AN ITEM FROM A SLICE
SUMMARY
EXERCISES
Lesson 13: Manipulating Maps
DEFINING A MAP
EMPTY MAPS
CREATING A MAP USING
MAKE
MAP LENGTH
RETRIEVING MAP ELEMENTS
CHECKING FOR A KEY
ITERATING THROUGH A MAP
DELETING MAP ELEMENTS
LITERAL DECLARATIONS IN MAPS
SUMMARY
EXERCISES
Lesson 14: Creating Methods
WORKING WITH METHODS
DEFINING A METHOD
USING POINTERS WITH METHODS
NAMING METHODS
WORKING WITH VALUE RECEIVERS AND ARGUMENTS
WORKING WITH POINTER RECEIVERS AND ARGUMENTS
SUMMARY
EXERCISES
Lesson 15: Adding Interfaces
CREATING AN INTERFACE
INTERFACES AND CODE REUSABILITY
STATIC VS. DYNAMIC INTERFACE TYPES
EMPTY INTERFACES
CHECKING AN INTERFACE TYPE
MULTIPLE INTERFACES
EMBEDDED INTERFACES
SUMMARY
EXERCISES
Lesson 16: Pulling It All Together: Building a Burger Shop
REQUIREMENTS FOR OUR APPLICATION
PLANNING THE CODE
CREATING THE STRUCTS
CREATING THE HELPER FUNCTIONS
TYING THE CODE TOGETHER
SUMMARY
THE FULL BURGER SHOP LISTING
PART III: Creating Job Ready Solutions in Go
Lesson 17: Handling Errors
ERRORS IN GO PROGRAMS
THE GO ERROR TYPE
CUSTOM ERROR HANDLING
ERROR METHODS
ERRORF
BLANK IDENTIFIERS
ERROR MESSAGES WITH STRUCTS
MULTIPLE CUSTOM ERROR MESSAGES
SUMMARY
EXERCISES
Lesson 18: Concurrency
USING CONCURRENCY
PARALLELISM
USING GOROUTINES
MULTIPLE GOROUTINES
WORKING WITH CHANNELS
CHANNELS WITH MULTIPLE GOROUTINES
CLOSING CHANNELS
ITERATING THROUGH A CHANNEL
SUMMARY
EXERCISES
Lesson 19: Sorting and Data Processing
SORTING
TIME AND DATE OPERATIONS
REGULAR EXPRESSIONS
SUMMARY
EXERCISES
Lesson 20: File I/O and OS Operations
READING A FILE
WRITING TO A FILE
WORKING WITH DIRECTORIES
COMMAND-LINE ARGUMENTS
SUMMARY
EXERCISES
Lesson 21: Pulling It All Together: Word Analysis in Go
EXAMINING THE DATA
READING THE REVIEW DATA
TOKENIZING AN INPUT STRING
CREATING A TOKENIZE FUNCTION
COUNTING THE WORDS IN EACH REVIEW
TOKENIZING AND COUNTING THE REVIEWS
DESIGNING IMPROVEMENTS
POSSIBLE FURTHER IMPROVEMENTS
FINAL CODE LISTING
SUMMARY
PART IV: Advanced Topics for Go Development
Lesson 22: Testing
TEST-DRIVEN DEVELOPMENT
TESTING LEVELS
THE TDD WORKFLOW
THE TESTING PACKAGE
TUTORIAL: TEST-DRIVEN DEVELOPMENT
BEHAVIOR-DRIVEN DEVELOPMENT
SUMMARY
EXERCISES
Lesson 23: API Development Tutorial
OVERVIEW AND REQUIREMENTS
STEP 1: CREATE THE DATASET AND A SIMPLE API
STEP 2: ADD A ROUTER: GORILLA MUX
STEP 3: RETRIEVE A RECORD
STEP 4: ADD A NEW RECORD
STEP 5: DELETE A RECORD
SUMMARY
EXERCISES
Lesson 24: Working with gRPC
WORKING WITH gRPC
SETTING UP THE SERVICES
CREATING A SERVER
CREATING A gRPC SERVER
CREATING THE CHAT SERVICE
UPDATING THE SERVER CODE TO INCLUDE THE CHAT SERVICE
CREATING THE
CHAT
PACKAGE
CREATING A CLIENT
RUNNING THE SERVER AND THE CLIENT
SUMMARY
EXERCISES
Lesson 25: Pulling It All Together: Using Smart Data
PROJECT OVERVIEW
DESIGNING OUR API
IMPLEMENTING THE gRPC SERVER
CREATING THE API
SUMMARY
Lesson 26: Using Modules
GETTING STARTED WITH MODULES
STEP 1: CREATE THE PROJECT DIRECTORY
STEP 2: CREATE YOUR PROGRAM(S)
STEP 3: CREATE A TEST PROGRAM
STEP 4: CREATE THE
GO.MOD
FILE
STEP 5: TEST THE MODULE
STEP 6: USING THE MODULE
NAMING MODULE FUNCTIONS
SUMMARY
EXERCISES
Appendix: File Permissions and Access Rights
CHANGING OTHER USER ACCESS RIGHTS IN LINUX
DIGITAL REPRESENTATION FOR PERMISSIONS
Index
Copyright
About the Authors
About the Technical Writer
About the Technical Editor
Acknowledgments
End User License Agreement
Lesson 3
Table 3.1 Integer data types in Go
Table 3.2 Implementation-specific integer data types in Go
Table 3.3 Float data types in Go
Lesson 4
Table 4.1 Common arithmetic operators
Table 4.2 Basic Go assignment operators
Table 4.3 Go relational operators
Table 4.4 Go Boolean operators
Table 4.5 Common Go math functions
Table 4.6 Go bitwise operators
Lesson 7
Table 7.1 2020 tax rates
Table 7.2 Taxes due based on tier
Lesson 19
Table 19.1 Time functions
Table 19.2 Date format constants
Appendix
Table A.1: Permission representations
Lesson 1
Figure 1.1: The Go Downloads page
Figure 1.2: The Go Setup Wizard
Figure 1.3: The Go End-User License Agreement
Figure 1.4: Specifying the folder where Go will be installed
Figure 1.5: Confirmation that Go is installed
Figure 1.6: Running the command prompt (Microsoft Windows 11)
Figure 1.7: The command prompt
Figure 1.8: Displaying your Go version
Figure 1.9: Using the
cd
command to change folders
Figure 1.10: Compiling a Go program
Figure 1.11: The output of the Hello, World! program
Figure 1.12: The Go Playground
Figure 1.13: Hello World in the Go Playground
Lesson 5
Figure 5.1: Visual representation of an
if
statement
Lesson 9
Figure 9.1: The index positions of
matrix
Lesson 12
Figure 12.1: Visualization of a slice
Lesson 18
Figure 18.1: Serial programming
Figure 18.2: Multiprogramming as compared to multiprocessing
Figure 18.3: A concurrency error
Figure 18.4: Parallel execution of a program
Figure 18.5: A CPU with multiple processors
Lesson 22
Figure 22.1: The Windows folder includes the files
c.out
,
coverage.html
,
Dol
...
Figure 22.2: The web page color-codes the lines of code. The results are sum...
Lesson 23
Figure 23.1: Creating a request
Figure 23.2: Sending our
GET
request
Figure 23.3: A
GET
request for the account information
Figure 23.4: Testing the request for a specific record
Figure 23.5: Setting up Postman to
POST
a new account
Figure 23.6: The return pane in Postman
Figure 23.7: Running a
GET
request to verify record was added
Lesson 24
Figure 24.1: Verifying Git and installing gRPC in Go
Figure 24.2: Running both the server and the client
Lesson 25
Figure 25.1: Architecture of our smart data app
Figure 25.2: Our new application architecture
Figure 25.3: Our client and server in action
Figure 25.4: Yahoo Finance API Specification
Figure 25.5: The expanded /v6/finance/quote option
Figure 25.6: Changing symbols to just AAPL
Figure 25.7: The Basic subscription for the Yahoo Finance API
Figure 25.8: The browser JSON response from the RPC call to the quote API
Figure 25.9: Running our programs in separate terminals
Figure 25.10: The landing endpoint for our API
Figure 25.11: Using the
getQuote
endpoint
Figure 25.12: Getting a TSLA quote with
getQuote
Figure 25.13: Calling the
getGeoLocationData
endpoint
Figure 25.14: Calling the
getGeoLocationData
endpoint
Appendix
Figure A.1: Viewing file permissions in Linux
Figure A.2: Adding multiple types of access rights in Linux
Cover
Title Page
Copyright
About the Authors
About the Technical Writer
About the Technical Editor
Acknowledgments
Introduction
Table of Contents
Begin Reading
Appendix: File Permissions and Access Rights
Index
End User License Agreement
iii
xxi
xxii
xxiii
1
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
377
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
iv
v
vi
vii
viii
679
HAYTHEM BALTI
CO-AUTHORED BY KIMBERLY A. WEISS
There are many programming languages a person can pick to create applications. Go, also known as Golang, is an open-source programming language that was designed at Google with a focus on simplicity and safety. Go first appeared to the public in 2009 and was officially released in 2012. Go is similar to the C programming language in the syntax and concepts that it uses. Go is a fast, small programming language that lets you focus on the solutions you want to build.
Go also provides features to make a developer's life easier. This includes garbage collection, memory safety, and structural typing. It also includes features such as built-in concurrency primitives, support of lightweight processes, an interface system, and more.
Whether you are looking to build standalone applications, build web apps, do concurrent programming, or perform a variety of other tasks, Go can help get you there. Other companies beyond Google are using Go, including Netflix, Ethereum, Splice, Twitch, and Uber. As result, Go has become a popular programming language.
The programming language is Go, but some people call it Golang. The Golang name comes from the domain where Go used to be located, which was golang.org. Go is now hosted on go.dev.
This book contains a full-fledged Go course that is used by the mthree Global Academy and The Software Guild to train our alumni in Go and other topics, such as data analysis and data science.
As already stated, Job Ready Go provides an overview of the Go programming language, also known as Golang. It also teaches you how to leverage the basics of Go to create programs that can process and analyze data, and it goes beyond the basics to present advanced topics such as using REST APIs and gRPC with Go.
As you read through this book, enter the code listings. Try playing with the code. Get it to execute, make changes to it, and see what happens. This is a book about learning to write code using the Go programming language, and the best way to do that is to play with actual code. By taking a hands-on approach to working with the code and doing the exercises, you will be better able to take what you learned to the next level.
Most importantly, this book (as well as the Job Ready series) goes beyond what many books provide by including lessons that help you pull together everything you are learning in a way that is more like what you would find in the professional world. This includes building a more comprehensive example than what you get in the standard short listings provided in most books. If you work through the “Pulling It All Together” lessons, then you will be better prepared for many of those Go jobs that are available.
As mentioned, this book is a complete Go programming course. It is broken into several parts, each containing a number of lessons. By working through the lessons in this book, you will not only learn Go programming, but you will be preparing yourself for a job using Go programming.
Part 1
: The Basics of the Go Programming Language
The first part of this book focuses on getting you set up to use Go. This includes help for installing Go and setting up the tools you will need to work through this book. You will also be shown how to enter and run Go programs. This section also provides an overview of the basics of Go, including syntax, basic data types, and control statements.
Part 2
: Organizing Code and Data in Go
The second part focuses on using the basic syntax learned in the first part and applying it to help organize your programming code using constructs such as functions, methods, and interfaces. It also focuses on working with and organizing data that is used in your application. This includes learning about data structures such as arrays, slices, maps, and structs.
Part 3
: Creating Job Ready Solutions in Go
The third part focuses on going beyond the basics and learning about concepts you'll need to build job ready solutions. This includes learning how to handle errors, working with concurrency, and working with data in files outside of your application. You'll also explore existing code that will let you add functionalities such as dates, times, and sorting to your applications. Most importantly, you'll learn the details needed to build solid, reusable, complex programs.
Part 4
: Advanced Topics for Go Development
In the last part of this book, we will focus on more advanced concepts that go beyond Go programming but that are important for Go programmers. This includes using test-driven development to build a Go application. It also includes working with REST APIs and gRPC to connect to and interact with processes and APIs that are outside of your own application.
There are several ways to get the help you need for this book.
As you work through the examples in this book, you should type in all the code manually. This will help you learn and better understand what the code does.
However, in some lessons, download files are referenced. You can download the files from www.wiley.com/go/jobreadygo.
If you believe you have found a mistake in this book, please bring it to our attention. At John Wiley & Sons, we understand how important it is to provide our customers with accurate content, but even with our best efforts an error may occur.
In order to submit your possible errata, please email it to our Customer Service Team at [email protected] with the subject line “Possible Book Errata Submission.”
Lesson 1: Getting Started with Go
Lesson 2: Understanding Go Basics
Lesson 3: Storing with Variables
Lesson 4: Performing Operations
Lesson 5: Controlling Program Flow with Conditional Statements
Lesson 6: Controlling Program Flow with Loops
Lesson 7: Pulling It All Together: Income Tax Calculator
Go is an open source programming language developed and distributed by Google. In this lesson, we will walk through the steps of installing Go on a computer running Microsoft Windows 10 or later.
By the end of this lesson, you will be able to:
Download and install Go on a local computer.
Test the installation to verify it works.
Create and run a Hello, World! program.
Demonstrate basic troubleshooting steps.
Use an online editor with Go.
Ensure consistent formatting of your Go programs.
NOTE There are also versions of Go for Apple macOS and Linux that you can download. The process should be somewhat similar to what is shown in this lesson.
There are several requirements for installing Go. First, you must have administrative rights on your computer. If you own the computer, you should have no problems. If you are using a work or school computer, contact your IT department if you run into permission problems during the installation process.
NOTE If you have used Go in the past and already have it installed on your computer, you can skip the installation instructions and go straight to the testing steps.
Alternatively, if you have an older version of Go that you would like to update, you might want to remove the existing version before installing the updated version.
You will also need a text or code editor to create Go programs. Go programs are written in plain text, so if you already have an editor you like, you can continue using it. If you have never used a code editor before or if you want to try a different one, you can use one of the following:
Visual Studio Code
(downloadable from
https://code.visualstudio.com
)
Atom
(downloadable from
https://atom.io
)
You can also find additional editors that support Go by going to the “Editor plugins and IDEs” page on the Go site. The page is found at https://go.dev/doc/editors.html. You can also use a plain-text editor such as Notepad if you prefer; however, an editor that supports Go, such as Visual Studio Code or Atom, will provide tools to help you with errors in your code.
The first step is to download the most current version of the installation files. You can find the files on Go's Downloads page at https://go.dev/dl. The instructions shown in Figure 1.1 are for version 1.17.2 for Windows, but you will likely see a more recent version on the page.
Click the link for your operating system in the Featured Downloads section of the page. This will download the necessary installation file or package for your operating system.
Figure 1.1: The Go Downloads page
Once you have downloaded the installation file, open it from your computer. In Windows, you can open it by simply clicking the filename. This will start the Setup Wizard, as shown in Figure 1.2.
Click Next to begin the installation. The next screen displays the End-User License Agreement, as shown in Figure 1.3.
Go is distributed under an open source license. This means that you can modify and/or redistribute the code if you wish, but you must include the same copyright notice in any package you distribute.
You should read through the licensing agreement and then select the check box to accept it. Click Next to continue the installation. The next screen, shown in Figure 1.4, asks you to specify the destination folder where Go will be installed.
Figure 1.2: The Go Setup Wizard
Figure 1.3: The Go End-User License Agreement
Figure 1.4: Specifying the folder where Go will be installed
You can either accept the default location or set a new location by entering the path to a folder or by clicking on Change to select a new location to install Go. Once you've entered the destination folder, click Next again. On the next screen, click the Install button to start the installation. Note that you might be prompted by Windows asking if you give permission to install the application. If so, you will need to indicate that it is okay.
When the installation is complete, you will see a confirmation message when the installation is complete, similar to what is shown in Figure 1.5. You can click the Finish button to close the wizard.
Figure 1.5: Confirmation that Go is installed
NOTE If you are using the MSI installer shown here, it will also set up your computer with the required environment variables during the installation.
After completing the installation, you should test to make sure Go works. To do this in Windows, start by opening a command-line window. Click the Start Menu and type cmd in the search box. You can then open the command prompt from the search results, as shown in Figure 1.6.
NOTE Alternatively, you can open the command prompt by pressing Windows key+R, entering cmd, and clicking the OK button.
Figure 1.6: Running the command prompt (Microsoft Windows 11)
The command prompt will open in a new window similar to Figure 1.7. You should see a prompt that ends in your username.
Figure 1.7: The command prompt
At the prompt, type the following command and press Enter:
go version
This command checks that Go is installed on your computer and displays the version number if it is. You should see a version that matches the one you just installed. Figure 1.8 shows version go1.17.2 installed.
If you get an error message instead of a version number, repeat the installation instructions and try again.
The default installation shown here used the MSI file. If entering the code snippet displayed the version number, then you should be ready to continue creating your first program, Hello World!.
If you downloaded a zip file instead of an MSI file, you will need to manually set up Windows environment variables before using Go. You can either delete the files created from the zip file and reinstall using the MSI file (which sets up the variables during the installation) or use the instructions provided in Go's Download and install page at https://go.dev/doc/install.
Figure 1.8: Displaying your Go version
With Go installed on your machine, you are ready to write and run your first Go program, Hello, World!. Using your preferred text or code editor (such as Atom or Visual Studio Code), create a file named gotest.go and save it to a known location, such as your Documents folder. In the example presented in Listing 1.1, the file is saved in Documents\GoLang. If you choose a different location, you will need to modify the instructions for compiling and running the program.
Make sure that the file has the filename extension .go. Most text or code editors will allow you to specify your own extension. Verify that the Save As box is set to All Files (or something similar) rather than a specific extension, such as .txt.
Add the code shown in Listing 1.1 to your new file.
package main
import "fmt"
func main() {
fmt.Println("Hello, world!")
}
At this time, you are not expected to understand all the code presented in Listing 1.1; however, it is worth taking a closer look. You start by creating a main package to serve as the starting point for your program. You follow this by using the import statement to import Go's formatting package fmt. The fmt package contains code that allows text to be printed to the screen.
NOTE The nice thing about using a package like fmt is that you can use it without having to worry about the code. In Listing 1.1, you can use fmt.Println without having to know what code is being used to actually do the printing.
You create a main() function in the third line of code, and you print the phrase “Hello, world!” by using Println from the fmt package you included. You don't need to understand how this works right now—just know that fmt.Println("") will print whatever is between the double quotes to the screen.
After entering the listing, make sure you save the file. You should leave the file open in your text editor in case you have problems running it. The compiler will read only the saved content in the file.
The next step is to compile the file. Compiling is the process of converting human-readable code into machine-readable code. Use the cd command to navigate to the folder where gotest.go is saved:
cd Documents\GoLang
For our example, we created the file in a subfolder, GoLang, of the Documents folder, so we will change to that folder. If you saved your file in a different folder, then you should navigate to that folder. Figure 1.9 shows the cd command being used in the command prompt window to change to the Documents\GoLang folder. If you executed the command correctly, you will see the folder name at the end of the prompt.
Figure 1.9: Using the cd command to change folders
Compile the program using the following command:
go build gotest.go
Simply enter this command at the command prompt and press Enter. The go build command will compile the file that is included, in this case, gotest.go. It may take a few moments to complete the compile, so as long as you don't see an error message, just wait. Eventually, the prompt will return, as shown in Figure 1.10.
Figure 1.10: Compiling a Go program
While you don't see anything on the screen, if you list the files in the directory, you should now see that an executable file with an .exe extension called gotest.exe exists.
You can now run the program by entering the program name on the command line and pressing Enter:
gotest
If the program was written and compiled correctly, you will see “Hello, World!” displayed, as shown in Figure 1.11.
Figure 1.11: The output of the Hello, World! program
The previous steps create and run a separate executable file using your program. The EXE file is useful if you want to share or run the program on a different computer. It is not necessary to create the EXE file if you simply want to test a program and don't plan to use the program somewhere else.
Another option is to compile and run the program in a single step, using this command:
go run
program_name
.go
You can try this using the same Hello, World! program. Verify that you are still in the correct directory in the command-line window (the directory where the gotest.go file is located) and run the command
go run gotest.go
You should see the following output immediately, without having to run a separate command to execute the program. This is the same output you saw before:
Hello, world!
If you had problems with this activity, you may have made one of the common mistakes many people make. Consider the following questions:
Did you navigate to the correct folder in the command prompt?
If you are not using the correct folder, you will see a message like the following when you run the
go build
command:
C:\Users\Student Name\Documents>go build gotest.go
can't load package: package gotest.go: cannot find package "gotest.go" in any of:
c:\go\src\gotest.go (from $GOROOT)
C:\Users\Student Name\go\src\gotest.go (from $GOPATH)
Make sure you know where the gotest.go file is located on your computer and navigate to that location using the cd command before compiling and running the program.
Did you enter the program from
Listing 1.1
without any typos or misspellings?
Most typing errors will be identified when you compile the program. If you see an error after running the
go build
command, read the error carefully to see where the problem is. As an example, consider the following error:
gotest.go:3:8: cannot find package "fnt" in any of:
c:\go\src\fnt (from $GOROOT)
C:\Users\Student Name\go\src\fnt (from $GOPATH)
In this example, fmt was misspelled as fnt in the 8th character on line 3 (3:8).
After correcting the error(s), save the file and try compiling it again.
Did you enter the commands on the command prompt line correctly?
Make sure you typed
go build
without any spelling mistakes. Also make sure you included the
.go
extension on your program filename.
When you entered the code from Listing 1.1, you should have followed the format that was presented, including the spacing and the indentation of the code. Whether you indent with three spaces, four spaces, or a tab will not matter when it comes time to run your program; however, in most job environments there will be posted standards.
By providing consistency in how you format your listings, it makes it easier to go from one listing to the next. Additionally, in organizations with multiple programmers, consistent formatting helps make the code easier to read and maintain.
Unlike many programming languages, Go has tried to reduce the controversy over formatting issues. Debates on whether to use three or four spaces, or to use a tab instead, can all be eliminated by using an included formatting option. You can do the formatting using the go fmt command as follows:
go fmt
mycode
.go
This will remove or fix minor formatting concerns in mycode.go. Listing 1.2 presents the same “Hello, World!” listing you saw earlier; however, the formatting has been poorly done. Enter this listing and name it gotest2.go.
package main
import "fmt"
func main() {
fmt.Println("Hello, world!") }
With the listing created and named gotest2.go, enter the following at the command line:
go fmt gotest2.go
You will see the name of the program displayed when Go has finished running. If you then open gotest2.go in an editor, you will see that the file has been updated with clean formatting:
package main
import "fmt"
func main() {
fmt.Println("Hello, world!")
}
NOTE Don't confuse the Go formatting tool with the Go fmt package that we mentioned in Listing 1.1. While the package and tool have the same name, they are different things.
Technically, you can have multiple Go versions installed on a single system. This is not only possible, but often very desirable, such as when you want to test specific code with multiple versions of the compiler. For example, you might want to make sure your open source package works with the latest compiler still being developed, but that it also works on the most recent stable version. It is beyond the scope of this book to cover installing multiple versions. You can, however, find instructions for doing this at https://go.dev/doc/manage-install.
If you want to be “job ready” with Go, then we recommend you install a copy on your machine. You do, however, have the option to use Go without installing Go tools locally, as shown in this lesson. When you simply want to test a piece of Go code quickly, then you might find it easier to jump online and use the Go Playground.
The Go Playground can be found at https://go.dev/play. This online tool is shown in Figure 1.12. As you can see, it is primarily an open screen with line numbers down the left and a few buttons on the upper right.
You can enter a listing in the main box, next to the line numbers. In Figure 1.13, the “Hello, World!” code from Listing 1.1 has been entered but with a mistake. Additionally, after entering the code, the Format button on the upper right was clicked to format the code (similar to using the go fmt command shown earlier).
With the code entered into the Go Playground, the Run button can be clicked to run the listing. This results in the output shown in the lower part of the window.
You can also see in Figure 1.13 that the “Hello, World!” program does have an error on line 6. You can see this in the error message at the bottom of the screen as well as from the highlighted line number 6. The Go Playground makes it easy to locate the right line number to make a fix. In this case, the closing double quote is missing.
Figure 1.12: The Go Playground
NOTE The Go Playground has limitations that are stated on the web page. You should, however, be able to use it for most of the lessons in the first three parts of this book.
Figure 1.13: Hello World in the Go Playground
In this lesson, the focus was on installing Go and confirming that it is ready to be used. When you are able to run the Hello, World! program successfully, you are ready to start coding with Go!
The following are a few useful online resources related to Go:
https://go.dev
: The official home page for Go
https://github.com/golang/go
: A GitHub-based learning wiki that includes many videos and exercises to help developers learn Go
The best way to learn is by doing something rather than just by reading about it. If you've not already done so, enter, compile, and run the program presented in this lesson. To further help confirm your understanding of this process, you should complete the following exercises on your own. The exercises for this lesson are:
Exercise 1.1
:
Counting Fun
Exercise 1.2
:
Counting More Fun
Just as you did with Listing 1.1 in this lesson, enter the code presented in Listing 1.3 in your editor and save it as countingfun.go. Don't worry about the details of how the code works. Rather, focus on entering the code as presented in the listing.
package main
import "fmt"
func main() {
ctr := 0
for ctr < 10 {
fmt.Println("ctr: ", ctr)
ctr += 1
}
}
After entering the code in your editor and saving it, use the go run command to run the program:
go run countingfun.go
If you entered the code correctly, you should see the following output:
ctr: 0
ctr: 1
ctr: 2
ctr: 3
ctr: 4
ctr: 5
ctr: 6
ctr: 7
ctr: 8
ctr: 9
If you get an error, try the troubleshooting tips that we presented earlier in this lesson to determine what went wrong.
Enter the code from Listing 1.4 and save it with the name morecodingfun.go.
package main
import "fmt"
func main() {
ctr := 0
for ctr < 20 {
fmt.Println("ctr: ", ctr)
ctr += 2
}
}
Can you find the changes? Compile and run the program to see the changes in action. When you run the code this time, the output should look like this:
ctr: 0
ctr: 2
ctr: 4
ctr: 6
ctr: 8
ctr: 10
ctr: 12
ctr: 14
ctr: 16
ctr: 18
You can continue to play with the numbers and the text in quotes to see what your changes do. Again, if you have trouble understanding what the code is doing, don't worry; we'll cover that in the rest of the lessons in this book.