Share E-Book

Go Programming in Easy Steps (McGrath, Mike)(Z-Library)

Author

,

Rating 3.5 AI initial rating

Log in to rate

Go
Language English

GO Programming in easy steps, 2nd edition is updated to cover the latest version of golang, and first illustrates the golang programming basics with variables, operators, flow control, and functions, before moving on to demonstrate Object-Oriented Programming (OOP) with golang. This book then shows how golang can handle user input, plus read and write files on your own system. The examples in GO Programming in easy steps, 2nd edition also demonstrate concurrent programming with goroutines for speed. Finally, the book illustrates how to create and interact with a golang web server on your own system. GO Programming in easy steps, 2nd edition has an easy-to-follow style that will appeal to: Anyone who wants begin programming in golang. Programmers looking to extend their skillset. Students who are studying programming at school or college. Those seeking a career in software development. This book makes no assumption that you have previous knowledge of any programming language, so is suitable for a beginner or a programming guru.

Format PDF
Size 4.5 MB
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
FULLY ILLUSTRATED EASY TO FOLLOW PLAIN ENGLISH IN FULL COLOR Control program flow with control structures. discover Google’s Go language (golang) Programming GO 2ndEdition M i k e M c G r a t h
Page 2
Declarations Component Syntax Variable var <name> <data-type> = <value> (Inferred) <name> := <value> Constant const <Name> = <value> Array var <name> [ <elements> ] <data-type> Slice <name> := make( [ ] <data-type> , <elements> ) Map <name> := make( map[ <key-data-type> ] <value-data-type> ) Channel <name> := make( chan <data-type> ) Struct type <name> struct { <field-name> <data-type> } Function func <name> ( <param-name> <data-type> ) <return-data-type> { return <return-value> } Interface type <name> interface { <method-name> <return-data-type> } Keywords Control Flow Declarations Types Concurrency Packages if break var struct go package else continue const interface chan import switch fallthrough type map select case goto func default return for defer range The tables below contain all 25 keywords of the Go programming language, and the declaration syntax used to create components in Go programs. The keywords have special significance, so may not be used for naming items in Go program code. Go Language Essentials
Page 3
M i k e M c G r a t h Second Edition GO Programming
Page 4
In easy steps is an imprint of In Easy Steps Limited 16 Hamilton Terrace . Holly Walk . Leamington Spa Warwickshire . United Kingdom . CV32 4LY www.ineasysteps.com Second Edition Copyright © 2026 by In Easy Steps Limited. 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 or retrieval system, without prior written permission from the publisher. Notice of Liability Every effort has been made to ensure that this book contains accurate and current information. However, In Easy Steps Limited and the author shall not be liable for any loss or damage suffered by readers as a result of any information contained herein. Trademarks All trademarks are acknowledged as belonging to their respective companies. In Easy Steps Limited supports The Forest Stewardship Council (FSC), the leading international forest certification organization. All our titles that are printed on Greenpeace approved FSC certified paper carry the FSC logo. Printed and bound in the United Kingdom ISBN 978-1-78791-052-2
Page 5
Contents Getting Started 7 Introducing the Go language 8 Installing the Go tools 10 Creating a Go test project 12 Installing Visual Studio Code 14 Observing language rules 16 Structuring Go programs 19 Summary 20 Storing Values 21 Creating variables 22 Displaying values 24 Converting data types 26 Fixing constant values 28 Pointing to stored values 30 Summary 32 Performing Operations 33 Doing arithmetic 34 Assigning values 36 Making comparisons 38 Assessing logic 40 Juggling bits 42 Specifying order 44 Summary 46 Controlling Flow 47 Testing conditions 48 Switching by case 50 Looping for count 52 Looping while valid 54 Breaking from loops 56 Going to labels 58 Summary 60 1 2 4 3
Page 6
Producing Functions 61 Creating a function 62 Passing values 64 Passing references 66 Returning values 68 Calling recursively 70 Enclosing anonymously 72 Passing functions 74 Handling errors 76 Separating files 78 Summary 80 Building Structures 81 Grouping data 82 Attaching methods 84 Embedding structs 86 Encapsulating features 88 Composing elements 90 Satisfying interfaces 92 Embedding interfaces 94 Summary 96 Creating Arrays 97 Starting arrays 98 Iterating elements 100 Slicing arrays 102 Forming slices 104 Comparing types 106 Mapping pairs 108 Summary 110 Harnessing Time 111 Getting dates 112 Getting times 114 Formatting date & time 116 Setting date & time 118 Recognizing time zones 120 Delaying time 122 Summary 124 5 6 7 8
Page 7
Managing Data 125 Uniting strings 126 Splitting strings 128 Finding characters 130 Converting strings 132 Calculating areas 134 Evaluating numbers 136 Rounding decimals 138 Generating randoms 140 Summary 142 Handling Input 143 Getting input 144 Buffering input 146 Requiring flags 148 Reading files 150 Writing files 152 Using tempfiles 154 Summary 156 Employing Concurrency 157 Creating goroutines 158 Awaiting completion 160 Making channels 162 Buffering channels 164 Selecting channels 166 Synchronizing goroutines 168 Using worker pools 170 Summary 172 Processing Requests 173 Listening for requests 174 Handling requests 176 Adding files 178 Serving files 180 Logging data 181 Serving responses 184 Summary 186 Index 187 9 10 11 12
Page 8
e examples in this book demonstrate features of the Go programming language (“golang”), and the screenshots illustrate the actual results produced by the listed code examples. Certain colorization conventions are used to clarify the code listed in the steps... Program code is colored black but keywords of the Go language are colored blue, literal text and numeric values are red, and code comments are green, like this: Grab the Source Code For convenience, the source code files from all examples featured in this book are available in a single ZIP archive. You can obtain this archive by following these easy steps: l1 Visit www.ineasysteps.com and log in, then navigate to Free Resources and click the Browse Now button in the Source code downloads and other book resources section l2 Next, find Go Programming in easy steps, 2nd edition in the list, then click on the hyperlink entitled All Code Examples to download the ZIP archive file l3 Now, extract the archive contents to any convenient location on your PC, such as the top-level directory at C:\Projects featured in the book How to Use is Book hello To identify the source code for the example programs described in the steps, an icon and project name appears in the margin alongside the steps: serverslice package main import "fmt" main( ) { // My First Go Program. fmt.Println( "Hello World!" ) } If you don’t achieve the result illustrated in any example, simply compare your code to that in the original example files you have downloaded to discover where you went wrong.
Page 9
Welcome to the exciting world of programming with Go. is chapter introduces the Go language and creates a development environment where you can produce your own Go programs. Introducing the Go language Installing the Go tools Creating a Go test project Installing Visual Studio Code Observing language rules Structuring Go programs Summary 8 10 12 14 16 19 20 Getting Started1
Page 10
8 G e tt in g S ta rt e d Introducing the Go language Go is a free open-source programming language created at Google by Robert Griesemer, Rob Pike, and Ken ompson – best known for development of the Unix operating system. Google released version 1.0 of the Go language (“golang”) in March 2012, since when it has gained widespread popularity. Go programs are written in plain text, then compiled into machine code by the Go compiler to produce an executable binary version. e aims of the Go programming language are to be expressive, fast, efficient, reliable, and simple to write. Some programming languages, such as C or C++, are fast and reliable but not simple. Conversely, other programming languages, such as Java or Python, are simple to write but not so efficient. Go is similar to the C programming language in many ways, and is sometimes referred to as a “C-like language” or “C for the 21st century”. But Go is much more than that as it adopts good ideas from many other programming languages, yet avoids features that lead to complexity or unreliability. Perhaps most importantly, Go introduces the ability to take advantage of multi-core CPU processing for concurrency using “goroutines” and “channels”. is provides the potential for the computer to deal with several things at the same time. Although the Go language does not have the class structures found in Object-Oriented Programming (OOP) languages such as C++ or Java, its features do provide some degree of encapsulation, inheritance, and polymorphism – the three cornerstones of OOP. You can discover many more programming language books in the In Easy Steps series – including C, C++, C#, Java, and Python. Visit www.ineasysteps.com to find out more. ASM Go Source Code Executable Binary Compiler (Intermediate Assembly Code)
Page 11
9 With so many programming languages to choose from, you may be wondering why you should choose to learn Go programming – so here are some of the advantages that Go offers: Simple Syntax e Go language is concise, like Python. It’s as simple to write as Python but is more efficient, like C++. is enables you to write code that is easy to read and maintain. Compiled Language e Go source code is compiled to binary machine code that can be read directly by the computer, instead of being interpreted every time a program runs. is enables the Go programs you write to run faster than programs written for interpreted languages like Python or PHP. e Go Compiler e Go compiler is fast and provides additional benefits, such as code optimization and error checking – it can detect unused variables in your code, missing imports that your code requires, and mistyped or invalid code. e Go compiler can also generate executable binaries for other operating systems. is enables you to compile your source code to run on multiple machines. Concurrency e Go language provides inherent support for concurrency with goroutines and channels. is enables you to write multi-threaded programs that can perform multiple tasks at the same time. Garbage Collection Automatic memory management is a key feature of the Go language. Its garbage collector runs concurrently with the program. is enables you to write program code without any concern for memory leakage. Static Typing Go is a statically typed language in which variables are explicitly declared to be of a particular fixed type. is enables errors to be caught early in the development process. You may well recognize other advantages as you gain experience with the Go language, but right now it’s time to get started... The Go gopher is the iconic mascot of the Go programming language. ...cont’d
Page 12
1 0 G e tt in g S ta rt e d The Go installer automatically sets an environment variable GOROOT, where the Go toolchain lives (C:\Program Files\Go). Go also uses a GOPATH directory for its module cache and installed binaries (typically C:\Users\<username>\go). Your own projects can be located anywhere, such as a custom C:\Projects directory. Installing the Go tools To get started with the Go programming language, you must first install the Go tools on your PC. ese allow you to build, run, and test programs written in the Go language. e Go tools are supplied together with lots of standard packages of useful trusted code that you can import into your own programs. e Go language installers are available for Windows, macOS, and Linux. l1 Open a web browser and visit https://go.dev/dl then download the appropriate installer for your system l2 When the download has completed, run the installer to launch the “Go Programming Language Setup Wizard” l3 Click Next to continue, then accept the license terms l4 Accept the suggested Destination Folder (usually at C:\Program Files\Go on Windows), then click Install to complete the installation
Page 13
1 1 The “WinKey” is the keyboard key labeled with the Windows logo. ...cont’d l5 To test that the installation was successful, first open a Terminal window – on a Windows system press WinKey + R together, to open a “Run” dialog, then enter cmd to open a “Command Prompt” window l6 At the command prompt, enter the command go version to see the current release version number, then enter the command go to see a list of Go tool commands Although there are quite a few Go tools, you will mostly use only the run tool to compile and run your programs.
Page 14
1 2 G e tt in g S ta rt e d Creating a Go test project Go programs are stored as plain text files organized into packages, with each file ending in a .go file extension. A typical Go project has a “go.mod” file that defines the project (module) name and dependencies, plus one or more .go files containing the program components. e program entry point is normally located in a “main.go” file containing a main( ) function starting point. In order to create an initial test project, you first need to choose a convenient top-level folder to store your Go programs, each in their individual subfolder. l1 On a Windows PC, open a Command Prompt window, and create a directory for all your Go programs – for example, a folder named “Projects” in the root directory mkdir C:\Projects\ l2 Move into the Projects folder, then create a subfolder for a test project named “hello” cd C:\Projects mkdir hello l3 Next, move into the hello folder, then enter this command to create a go.mod definition file – to give your project a unique module path cd hello go mod init example.com/hello hello The go mod file specifies the Go language version. Go version 1.26, and its minor releases, defaults to Go language version 1.25.0 to maximize compatibility. If you see a suggestion to run go mod tidy, it can be safely ignored for now. It is only useful when importing external packages.
Page 15
1 3 ...cont’d l4 Now, launch a plain text editor, such as Windows’ Notepad app, ready to create a main.go source code file notepad main.go l5 Next, in main.go, precisely insert this Go source code package main import "fmt" func main( ) { fmt.Println( "Hello, Go!" ) } l6 Save the source code file in the hello folder l7 Finally, enter a command to run the entire module contained within this folder (go run, space, full stop) – to see the program output go run . Use the tree command to ensure your project folder structure looks like this:
Page 16
1 4 G e tt in g S ta rt e d Installing Visual Studio Code Go developers commonly use the Visual Studio Code app because it provides a fast, lightweight editing experience with strong Go tooling built in, thanks to the official Go extension that adds features like IntelliSense, auto-imports, debugging, testing, and module awareness. It’s free, cross-platform, and highly customizable, which makes it appealing for both beginners and experienced developers. l1 Go to https://code.visualstudio.com then click the Download button to grab the VSCode setup executable l2 Run the installer and choose the Add to PATH option l3 Launch Visual Studio Code and click the Extensions icon on the left sidebar l4 Type Go in the Search box to find the official extension authored by the Go team at Google, then click Install – to fetch Go tools for Visual Studio Code l5 Now, open the test project created earlier by selecting File, Open Folder and choosing C:\Projects\hello
Page 17
1 5 ...cont’d l6 Select the main.go file in the Explorer panel, to see the Go code appear in the Visual Studio Code editor l7 On the Visual Studio Code menu bar, select View, Terminal to open a Terminal panel – by default, this will appear below the editor panel l8 In the Terminal, type the command to run the entire module contained within this folder (go run, space, full stop) – to see the program output l9 Select File, Preferences, Settings, then search for “format on save” and check the Format On Save box – to have your code auto-formatted whenever you save it The Terminal window can run many different shells. It is configured in our examples to use the familiar Command Prompt shell for clarity.
Page 18
1 6 G e tt in g S ta rt e d Observing language rules It is important to observe the following rules to ensure you are writing correct Go syntax, in best Go code style, and producing optimal Go program behavior: Syntax & Structure • Every Go file starts with a package declaration, stating a package name. is tells Go how the file fits into the module. A package main declaration is required for executables. • e import keyword is used to import additional packages. Unused imports cause compile errors. Single imports should appear in a single line. Multiple imports must be grouped in a multi-line block enclosed in parentheses: import "fmt" import ( "fmt" "strings" ) • Function definitions start with the func keyword, followed by a name of your choice and a pair of braces. e opening brace must be on the first line – after the function name: func <function-name> { } Formatting & Style • Go has one canonical style. You can issue a go fmt command to apply this style. Use Visual Studio Code’s Format On Save option to keep everything consistent. • Unlike other programming languages, Go’s formatter uses tabs for indentation. Use tabs, not spaces, for indentation. • Go encourages clarity over cleverness. Keep lines short and readable.
Page 19
1 7 Variables & Types • Use short variable declarations when the type is obvious. For example, x := 10 is preferred, as the integer type is obvious. • Use the var keyword when you need to explicitly specify a type. For example, var count int specifies an integer type. • Avoid unused variables. Go treats unused variables as errors to keep code clean. Case Sensitivity • Go is case sensitive. is means that count, Count, and COUNT are all different identifiers. • Capitalization controls visibility: - Uppercase gets exported (public) - Lowercase doesn’t get exported (private) • Follow Go naming conventions. Acronyms stay consistently capitalized: - HTTPServer, not HttpServer and URL, not Url Comments • Use // for single-line comments. For example: // Print a greeting fmt.Println("Hello") • Use /* ... */ for multi-line comments. For example: This is a multi-line comment. • Write documentation comments above declarations. ey must start with the name of the thing being documented: // Add returns the sum of two integers. func Add(a, b int) int { return a + b } • Explain why, not what. // BAD: Increment x by 1 x = x + 1 // GOOD: Move to the next record x++ ...cont’d
Page 20
1 8 G e tt in g S ta rt e d ...cont’d Control Flow • Do not add parentheses around if, for, or switch conditions. For example, use if x > 5, not if (x > 5) • Use the for keyword for all loops. Go has no while keyword – for covers all looping patterns. For example: • Use switch instead of long if/else chains. Go’s switch is powerful and readable. For example: for i := 0 ; i < 5 ; i++ { fmt.Println( i ) } Error Handling • Always check errors. In Go, errors are values, not exceptions. For example: day := "Saturday" switch day { case "Saturday", "Sunday" : fmt.Println("Weekend") default : fmt.Println("Weekday") } • Return early on error to keep code flat and readable. • Don’t use the built-in panic function for normal errors. You should only use this function for truly exceptional situations. if err != nil { return err }
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List