GoLang: The Ultimate Guide

This document was uploaded by one of our users. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

Simply click on the Download Book button.

Yes, Book downloads on Ebookily are 100% Free.

Sometimes the book is free on Amazon As well, so go ahead and hit "Search on Amazon"

Go, also known as GoLang, is a Google-developed open-source, compiled, and statically typed computer language. Go is a general purpose programming language with a straightforward syntax and a large standard library. The building of highly accessible and scalable web apps is one of the primary areas where GoLang is widely used. It may also be used to develop command-line programs, desktop applications, and even mobile apps.

Go was designed from the ground up for networking and infrastructure-related applications. It was developed as a replacement for popular server-side languages like Java and C++. The Go programming language aims to combine the efficiency and safety of a statically typed, compiled language with the simplicity of programming of an interpreted, dynamically typed language. It also aspires to be cutting edge, with networked and multicore computer capabilities.

Why Should You Learn GoLang?

GoLang is becoming one of the most popular languages, which means that learning it can open up new doors of opportunity and even help you land a job at various companies that use Go extensively.

Ease of writing concurrent programs, fast compilation, simple syntax, and static linking are some of the features that make Go an ideal candidate for developing various applications.

This Book Includes:

• A step-by-step approach to problem solving and skill development

• A quick run-through of the basic concepts, in the form of a "Crash Course"

• Advanced, hands-on core concepts, with a focus on real-world problems

• Industry-level coding paradigms, and a practice-oriented explanatory approach

• Special emphasis on writing clean and optimized code, with additional chapters focused on coding methodology

Author(s): Sufyan bin Uzayr
Publisher: CRC Press
Year: 2022

Language: English
Pages: 365
City: Boca Raton

Cover
Half Title
Title Page
Copyright Page
Contents
Acknowledgments
About the Author
CHAPTER 1: Crash Course in GoLang
IS IT REFERRED TO AS Go OR GoLang?
WHAT IS THE PURPOSE OF GoLang?
WHY IS Go SO POPULAR?
Other Programming Languages vs. Go
Python vs. Go
But How Does Go Stack Up against Python?
SHOULD WE STUDY Go?
Go PROGRAMMING FEATURES
WHAT MAKES GoLang SUPERIOR TO OTHER COMPUTER LANGUAGES?
GoLang’s Core Capability
Multithreading and Concurrency
From within, Go Empowers Hardware
Unmatched Simplicity of Go
Built-in Testing and Profiling Framework
Easy Learning Curve
BEGINNING WITH Go
Text Editor
Finding a Go Compiler
INSTALL Go ON WINDOWS
How Can We Know Which Go Language Version Is Preinstalled?
Downloading and Installing Go
WRITING THE FIRST Go PROGRAM
Why Is There a “Go Language”?
What Is Missing in Go That the Other Languages Have?
Hardware Restrictions
The Upsides and Downsides of the Go Language
TERMINAL
The Open Terminal Tool Window
Start the New Session
INSTALL Go ON Mac
Making Our First Program
Implement a Go Program
Do Go Programs Interact with Programs Written in C/C++?
HOW CAN WE CREATE AN EMPTY FILE IN GoLang?
HOW TO MAKE A DIRECTORY IN Go
HOW TO READ AND WRITE A Go Program
HOW DO WE RENAME AND TRANSFER A FILE IN GoLang?
HOW TO READ A FILE LINE BY LINE AND CONVERT IT TO A STRING
BASIC SYNTAX
Tokens
Line Separator
Comments
Identifiers
Keywords
Whitespace
DATA TYPES IN Go
Numbers
Booleans
Strings
VARIABLES IN Go
Declaring a Variable
Employing the var Keyword
Using the Short Variable Declaration
CONSTANTS
How Should We Declare?
Untyped and Typed Numeric Constants
Numeric Constant
String Literals
Boolean Constant
VARIABLE SCOPE IN Go
Local Variables
Global Variables
DECLARATION OF MULTIPLE VARIABLES
SHORTHAND DECLARATION
OPERATORS IN Go
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
CONTROL STATEMENTS
if Statement
if…else Statement
Nested if Statement
if..else..if Ladder
SWITCH STATEMENT
Expression Switch
Type Switch
ARRAYS
Creating and Using an Array
Using var Keyword
Using a Shorthand Declaration
Multidimensional Array
How Do You Copy an Array into Another Array?
How Can We Pass an Array to a Function?
SLICES
Slice Declaration
Slice Components
How Do We Create and Begin a Slice?
Using Slice Literal
Using an Array
Using an Existing Slice
Using the make() Function
How to Iterate over a Slice
Using the for Loop
Using Range in a for Loop
Using a Blank Identifier in a for Loop
Slice Composite Literal
How to Sort a Slice of ints
Ints
IntsAreSorted
How Do We Trim a Slice of Bytes in GoLang?
How Do We Split a Slice of Bytes?
STRING
String Literals
Using Double Quotes (“”)
Using Backticks(“)
How Do We Trim a String?
Trim
TrimLeft
TrimRight
TrimSpace
TrimSuffix
TrimPrefix
How to Split a String
Split
SplitAfter
SplitAfterN
MAPS
How Do We Create and Initialize Maps?
Simple
Using the make() Function
WHAT IS A BLANK IDENTIFIER (underscore)?
DEFER KEYWORD
PANIC IN GoLang
RECOVER
CLOSURES
RECURSION
POINTERS
What Are Points Used For?
Pointers Declaration and Initialization
Declaring a Pointer
Pointer Initialization
Dereferencing a Pointer
In GoLang, How Can We Instantiate a Struct Using the New Keyword?
Pointers to a Function
Create a Pointer and Pass It to the Function
Passing an Address of the Variable to Function Call
Pointer to a Struct
Pointer to Pointer in Go
How to Declare a Pointer to a Pointer
Comparing Pointers
== operator
!= operator
GoLang STRUCTURES
Pointers to a Struct
GoLang’s NESTED STRUCTURE
GoLang METHODS
Method with the Struct Type Receiver
Method with the Non-Struct Type Receiver
Methods with the Pointer Receiver
INTERFACES
How Do We Make an Interface?
How to Implement Interfaces
Why Are Go Interfaces Wonderful?
Redundant Functions
INHERITANCE
POLYMORPHISM USING INTERFACES
CHAPTER 2: Test-Driven Development
DEVELOPING A NEW PROJECT
MAKING Go FILES
RUN TESTS
A TEST THAT FAILED
THE FUNCTION BEING TESTED
WRITING A TEST-FIRST FUNCTION
REFACTORING Go WITH Go/ANALYSIS
Invoke the Refactoring Command
Conflicts Resolve
Configure the Refactoring Options
My Top Four Go Refactoring Approaches
Method of Extraction
Method of Move
Create a Parameter Object
Replace Symbolic Constant with Magic Number
REFACTORING OUR FIRST Go CODE
Include a Parameter Check
Add String Formatting
Take Out the Code
Write a Test
GoLang ERROR HANDLING
Errors in GoLang
Creating Our Own Mistakes
Errors Caused by Strings
Data Custom Mistakes
Handling Errors in Functions
Defer
Panic
Recover
Error Wrapping
Casting Errors
WRITE UNIT TESTING IN Go
Beginning
Unique to Go
Setup and Teardown
Testing within the Same Package
Five Basic Techniques and Strategies for Developing GoLang Unit Tests
CHAPTER 3: Packaging in GoLang
PACKAGES IN GoLang
Workspace
Main Package
Import Packages
Install Third-Party Packages
Init Function
Important Considerations
Giving the Packages Names
Code Exported
Essential Go Packages and Libraries
Awesome Go
GoLang-Set
Color
Now
Gen
Gorm
Goose
Glide
Ginkgo
Etcd
NSQ
Docker
Kubernetes
DEPENDENCY MANAGEMENT
Versioning
Modules
Installing Dependencies
Dependencies Must Authenticate
Remove Unused Dependencies
Installing Dependencies That Are Missing
Updating the Versions of Dependencies
Listing Dependencies
Module vs. Package
Naming
Fetching Packages
CHAPTER 4: Handling Concurrency
CONCURRENCY
Illustration of the Sleeping Barber Issue
Example of a Producer-Consumer Problem
Goroutines – CONCURRENCY IN GoLang
Go Concurrent Programming
Issues with Multithreading
How to Create a Goroutine
MULTIPLE Goroutines
What Is the Difference between Parallelism and Concurrency?
Goroutines Provide Several Advantages over Threads
COMMUNICATE TO SHARE MEMORY
HOW TO USE Goroutines TO ACCESS SHARED RESOURCES
Access Shared Resources Using Goroutines
Using Mutual Exclusion to Get Access to Shared Resources
Using Atomic Counters to Get Access to Shared Resources
Concurrency Issues
Concurrency Disadvantages
Benefits of Concurrency
Problems with Concurrency
CHAPTER 5: GoLang for JavaScript Developers
FLOW CONTROL
Loop Control Statements in Go
Break Statement
Goto Statement
Continue Statement
TYPES
Basic Types
Numbers
Booleans
Strings
Type Conversion
Type Assertion
Structs
Initializing
Composition vs. Inheritance
HOW DO YOU MAKE MODULES IN GoLang?
Adding Dependencies to the Go Module
PACKAGE MANAGEMENT USING Go MODULES
What Exactly Is the Go Module?
Starting Out
Module Initializing
Setting Up Dependencies
Eliminating Unnecessary Dependencies
Updating a Dependency Version
ERROR HANDLING
Error Type Representation
Various Approaches to Getting More Information from an Error
Don’t Ignore Errors
IN GoLang, THERE ARE SEVERAL TECHNIQUES TO COMPARE STRINGS
Making Use of Comparison Operators
Using the Compare() Method
FUNCTIONS IN Go
Function Declaration
Function Calling
Function Arguments
FUNCTION RETURNING MULTIPLE VALUES
Giving Names to the Return Values
VARIADIC FUNCTIONS
ANONYMOUS FUNCTION
GoLang main AND init FUNCTIONS
main() Function
init() Function
CHAPTER 6: Code Optimization
A PATTERN FOR OPTIMIZING Go
Why Is Code Optimization Necessary?
Code Base That Is Cleaner
Improved Consistency
Pages That Load Faster
Improved Code Readability
More Efficient Refactoring
Easier to Understand Debugging
Enhanced Workflow
Code Upkeep Is Now Easier
Improved Feature Development
The Ultimate Guide to GoLang Performance Optimization
GoLang Performance Hints That Have Been Proven and Tested
Optimization of Resource Efficiency
Optimization of Latency in GoLang
Efficiency of Algorithms
Patterns of GoLang Application Performance
Use Goroutines Sparingly
CPU Work Should Parallelize
Asynchronous I/O Operations
Keep an Eye on Our Timeouts
Memory Should Not Allocate in Hot Spots
Make Use of Lock-Free Algorithms
Prefer Read-Only Locks
Reduce or Eliminate the Use of ‘cgo’
Make Use of Buffered I/O
Use Binary Instead
StringBuffer and StringBuilder Are Preferable
Make Use of Regular Expressions
Slices Should Preallocate
Select Protocol Buffers and MessagePack as Our Options
For Maps, Use int Rather Than a String
GoLang FOR SECURE CODING
Stuck in a Rut with Manual Security
With Go, There Is a Need for Integrated, Automated Security
How Does Instrument-Based Security Work in the Go Pipeline?
Contrast Goes Above and Beyond with Modern Application Security
Go Security Best Practices
Verify the Input Entries
Make Use of HTML Templates
Protect Ourselves against SQL Injections
Encrypt Any Sensitive Data
Make HTTPS Communication Mandatory
Be Cautious of Mistakes and Logs
BEST PRACTICES FOR GoLang
Syntax
Assign Datatypes to Newly Created Variables
Do Not Declare a Variable or Import a Package That We Do Not Require
Follow Proper Naming Conventions
Make Use of Comments to Help in Knowledge Transfer
Simple, Readable, and Maintainable Code
Avoid Nesting by Dealing with Mistakes First
Avoid Utility Repeats
To Address Exceptional Circumstances, Use the Type Switch
Go Code Organization
For Use in CI/CD Workflows
Make Use of Go Modules
Ensure Immutability and Availability Using GOPROXY
CHAPTER 7: GoLang Tutorials and Projects
WEB APPLICATION TO GENERATE QR CODE IN GoLang
Install the Necessary Package
Development
Main.go Source Code
Generator.html Source Code
Implementation
SETTING UP THE Go HTTP CLIENT
HTTP Client in GoLang
POST and GET Requests
Adding Request Headers
Our Requests Are Being Authorized
WHAT IS THE GoLang REST API?
Using GoLang to Consume a REST API
Project Setup
Imports
Example of a Response
Struct
Code
Run the Project
APPRAISAL
CHEAT SHEET
BIBLIOGRAPHY
INDEX