Statistics
7
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-02-25

AuthorRahul Sid Patil

This book is a comprehensive guide designed to introduce newcomers to Go (Golang). It covers the essential topics that you would need to build a solid foundation in Golang, including basic syntax, data types, control structures, functions, and packages. Along with the basics of the language, you will also learn how to set up a development environment, integrate Visual Studio Code, and use Git and GitHub for version control. Learn the language through practical, hands-on interactive exercises using Go Playground and real-world projects. In the book you can work through detailed, step-by-step instructions from environment setup to project deployment, and easily follow along without prior experience. Each chapter builds progressively, guiding you from writing simple programs to developing a useful CLI tool and a basic web service. By treating each example as a GitHub project, the book ensures you gain experience in project management and collaborative development. Topics such as error handling, testing, and concurrency are covered in depth, providing you with the skills needed to write efficient and reliable Go code. The appendix includes valuable resources like quick reference guides and best practices for Go programming. This book is an indispensable resource for you in Go due to its highly practical, hands-on approach with detailed, step-by-step instructions, comprehensive integration with modern development tools, and real-world project examples. What You'll Learn: • Basic Go Programming Concepts like variables, data types, control structures, functions, and packages • Setting up a Go development environment and configuring Visual Studio Code for Go projects • Building, deploying, and maintaining a useful Command-Line Interface (CLI) tool in Go • Applying Go programming concepts through hands-on projects and real-world examples Who this book is for: Software architects and engineers, students, hobbyists, educators and trainers

Tags
No tags
ISBN: 8868814412
Publisher: Apress
Publish Year: 2025
Language: 英文
Pages: 338
File Format: PDF
File Size: 9.3 MB
Support Statistics
¥.00 · 0times
Text Preview (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.

Let Us Go! A Complete Beginner’s Guide to Golang Programming and Development — Rahul Sid Patil
Let Us Go! A Complete Beginner’s Guide to Golang Programming and Development Rahul Sid Patil
Let Us Go!: A Complete Beginner’s Guide to Golang Programming and Development ISBN-13 (pbk): 979-8-8688-1441-9 ISBN-13 (electronic): 979-8-8688-1442-6 https://doi.org/10.1007/979-8-8688-1442-6 Copyright © 2025 by Rahul Sid Patil This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Anandadeep Roy Editorial Assistant: Jessica Vakili Cover designed by eStudioCalamar Cover image designed by Freepik (www.freepik.com) Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza, New York, NY 10004. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny @springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a Delaware LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail booktranslations@springernature.com; for reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub. For more detailed information, please visit https://www.apress. com/gp/services/source-code. If disposing of this product, please recycle the paper Rahul Sid Patil Pune, Maharashtra, India
I dedicate this book to all the budding Gophers and cloud- native developers who are shaping the future of modern, intelligent, and cloud-native enterprise software. Your passion and innovation are building the foundation for a smarter and more connected world, driving technology to make life better for humankind. May this book serve as a guide and inspiration on your journey.
v Table of Contents About the Author �������������������������������������������������������������������������������xiii About the Technical Reviewer ������������������������������������������������������������xv Acknowledgments ����������������������������������������������������������������������������xvii Introduction ���������������������������������������������������������������������������������������xix Chapter 1: Let Us Go on the Playground �����������������������������������������������1 1.1 Introduction .....................................................................................................1 1.2 The Go Playground ..........................................................................................1 1.3 Writing and Running Basic Programs .............................................................2 1.3.1 Hello World .............................................................................................2 1.3.2 Values .....................................................................................................3 1.3.3 Variables .................................................................................................4 1.3.4 Constants ................................................................................................7 1.4 Control Flow ..................................................................................................10 1.4.1 For Loop ................................................................................................10 1.4.2 If/Else ...................................................................................................13 1.4.3 Switch...................................................................................................14 1.5 Pointers .........................................................................................................16 1.5.1 Declaring and Using Pointers ...............................................................16 1.6 Arrays ............................................................................................................17 1.6.1 Declaring and Using Arrays ..................................................................17
vi 1.7 Slices ............................................................................................................18 1.7.1 Creating and Using Slices .....................................................................18 1.8 Maps .............................................................................................................19 1.8.1 Declaring and Using Maps ....................................................................19 1.9 Functions ......................................................................................................20 1.9.1 Declaring and Using Functions .............................................................20 1.10 Multiple Return Values ................................................................................21 1.10.1 Using Multiple Return Values ..............................................................22 1.11 Variadic Functions .......................................................................................23 1.11.1 Declaring and Using Variadic Functions .............................................23 1.12 Closures ......................................................................................................24 1.13 Recursion ....................................................................................................26 1.14 Strings and Runes .......................................................................................27 1.14.1 Strings ................................................................................................27 1.14.2 Runes .................................................................................................28 1.15 Structs.........................................................................................................29 1.16 Methods ......................................................................................................30 1.17 Interfaces ....................................................................................................31 1.18 Errors ..........................................................................................................33 1.19 Goroutines ...................................................................................................34 1.20 Channels .....................................................................................................36 1.21 Select ..........................................................................................................37 1.22 Time ............................................................................................................38 1.22.1 Using the time Package ......................................................................39 1.23 Reading Files ..............................................................................................40 1.23.1 Reading a File Line by Line .................................................................40 1.24 Writing Files ................................................................................................42 1.24.1 Writing Text to a File ...........................................................................42 Table of ConTenTs
vii 1.25 Testing and Benchmarking ..........................................................................43 1.25.1 Writing a Unit Test ...............................................................................44 1.26 Command-Line Arguments .........................................................................45 1.27 HTTP Server ................................................................................................47 1.28 HTTP Client ..................................................................................................48 1.29 Context ........................................................................................................50 1.30 Summary.....................................................................................................52 Chapter 2: Setting Up the Go Workspace and VSCode IDE ������������������53 2.1 Introduction ...................................................................................................53 2.2 VSCode IDE and Golang Workspace Setup on Windows ................................54 2.2.1 Installing Go ..........................................................................................54 2.2.2 Installing and Setting Up VSCode for Golang Development ..................56 2.2.3 Setting Up a Go Workspace Using VSCode ...........................................57 2.3 VSCode IDE and Golang Workspace Setup on WSL Ubuntu ...........................58 2.3.1 What Is WSL? ........................................................................................58 2.3.2 How to Enable WSL on Windows ..........................................................59 2.3.3 How to Search and Install Ubuntu on WSL ...........................................59 2.3.4 How to Configure WSL Ubuntu to Access the Internet Connected to Host PC ......................................................................................................60 2.3.5 Install Go on WSL Ubuntu .....................................................................61 2.3.6 Install and Set Up VSCode for Golang Development Along with Required Go Extensions on WSL Ubuntu .......................................................62 2.3.7 Set Up Go Workspace Using VSCode, Create, and Execute Hello World Program in the Go Workspace .............................................................63 2.4 VSCode IDE and Golang Workspace Setup on Ubuntu ...................................64 2.4.1 Install Go ...............................................................................................64 2.4.2 Install and Set Up VSCode for Golang Development .............................66 2.4.3 Set Up Go Workspace Using VSCode ....................................................67 Table of ConTenTs
viii 2.5 VSCode IDE and Golang Workspace Setup on macOS ...................................68 2.5.1 Install Go ...............................................................................................69 2.5.2 Install and Set Up VSCode for Golang Development .............................70 2.5.3 Set Up Go Workspace Using VSCode ....................................................71 2.6 Summary.......................................................................................................72 Chapter 3: Setting Up and Maintaining Local and Remote GitHub Repository �������������������������������������������������������������������������������75 3.1 Introduction ...................................................................................................75 3.2 Introduction to Git and GitHub .......................................................................75 3.2.1 Basics of Version Control ......................................................................76 3.2.2 Setting Up Git on Your Local Machine ...................................................78 3.3 Creating a GitHub Repository ........................................................................79 3.3.1 Creating and Cloning Repositories .......................................................79 3.3.2 Committing Changes and Pushing to GitHub ........................................80 3.4 Using Git with VSCode ...................................................................................81 3.4.1 Managing Repositories from VSCode ...................................................81 3.4.2 Handling Branches and Pull Requests ..................................................82 3.5 Exercise: Create Your Own GitHub Repository ..............................................82 3.6 Summary.......................................................................................................84 Chapter 4: Let Us Go Deep Dive ����������������������������������������������������������87 4.1 Introduction ...................................................................................................87 4.2 Why This Chapter Matters .............................................................................88 4.3 What You’ll Learn ..........................................................................................88 4.4 How to Approach This Chapter ......................................................................89 4.5 Useful Go Tools ..............................................................................................89 4.5.1 go run ...................................................................................................89 4.5.2 go build .................................................................................................90 Table of ConTenTs
ix 4.5.3 go test ..................................................................................................91 4.5.4 go fmt ...................................................................................................91 4.5.5 go mod .................................................................................................92 4.5.6 go install ...............................................................................................92 4.6 Data Types .....................................................................................................93 4.6.1 Basic Data Types ..................................................................................93 4.6.2 Composite Data Types ........................................................................107 4.7 Operators and Expressions .........................................................................128 4.7.1 Arithmetic Operators ..........................................................................128 4.7.2 Comparison Operators ........................................................................130 4.7.3 Logical Operators ...............................................................................131 4.8 Control Flow ................................................................................................135 4.8.1 Conditional Statements ......................................................................136 4.8.2 Loops ..................................................................................................139 4.8.3 Defer, Panic, and Recover ...................................................................143 4.9 Functions ....................................................................................................150 4.9.1 Function Declaration and Calling ........................................................150 4.9.2 Parameters and Return Values ...........................................................151 4.9.3 Variadic Functions ..............................................................................153 4.9.4 Anonymous Functions and Closures ...................................................154 4.9.5 Function Variables and Higher-Order Functions .................................155 4.9.6 Recursion ...........................................................................................156 4.10 Pointers in Go ............................................................................................160 4.10.1 Understanding Pointers ....................................................................160 4.10.2 Pointer Variants and Operations .......................................................162 4.10.3 Pointers in Functions ........................................................................163 4.10.4 Pointers with Arrays, Slices, and Maps ............................................164 4.10.5 Summary of Pointer Types in Go .......................................................167 Table of ConTenTs
x 4.11 Structs and Methods .................................................................................170 4.11.1 Defining Structs ................................................................................170 4.11.2 Methods on Structs ..........................................................................172 4.11.3 Pointer Receivers vs. Value Receivers ..............................................174 4.12 Interfaces in Go .........................................................................................179 4.12.1 Defining and Implementing Interfaces .............................................180 4.12.2 Types of Interfaces in Go ..................................................................183 4.12.3 Interface As Function Parameters and Return Types ........................187 4.12.4 Empty Interface and Type Assertion .................................................190 4.12.5 Reflection with Interfaces ................................................................193 4.12.6 Interface Internals: Memory Model ..................................................196 4.12.7 Interface Design Patterns in Go ........................................................199 4.13 Concurrency with Goroutines ....................................................................210 4.13.1 Introduction to Goroutines ................................................................210 4.13.2 Synchronization of Goroutines with Mutex and WaitGroups .............224 4.14 Error Handling ...........................................................................................231 4.14.1 Error Types in Go...............................................................................231 4.14.2 Handling Errors Gracefully ................................................................233 4.14.3 Creating Custom Errors ....................................................................235 4.15 File I/O .......................................................................................................239 4.15.1 Reading from and Writing to Files ....................................................239 4.15.2 Working with Buffers ........................................................................241 4.15.3 Error Checking in File Operations .....................................................243 4.16 Unit Testing ...............................................................................................249 4.16.1 Testing and Benchmarking ...............................................................249 Table of ConTenTs
xi 4.17 Useful Go Programming Constructs ..........................................................253 4.17.1 Timers and Tickers ...........................................................................253 4.17.2 Worker Pools .....................................................................................255 4.17.3 Contexts ............................................................................................257 4.17.4 Circuit Breakers ................................................................................259 4.18 Summary...................................................................................................263 4.18.1 What’s Next? .....................................................................................264 Chapter 5: Building and Deploying a Useful CLI Tool ������������������������265 5.1 Introduction .................................................................................................265 5.2 What Is a CLI Tool? ......................................................................................266 5.2.1 Common Use Cases ...........................................................................266 5.2.2 Popular CLI Tools Written in Go ..........................................................266 5.3 Introduction to Open Source Software ........................................................267 5.3.1 Benefits ..............................................................................................267 5.3.2 Best Practices ....................................................................................267 5.4 Step by Step: Build and Release a CLI Password Generator in Go ..............267 5.4.1 Problem Statement ............................................................................267 5.4.2 Create GitHub Repository ...................................................................268 5.4.3 Set Up Go Module ...............................................................................268 5.4.4 Write the Go Code ...............................................................................268 5.4.5 Add a Makefile ....................................................................................270 5.4.6 Add Unit Tests (Optional but Recommended) .....................................271 5.4.7 Add License and README ..................................................................271 5.4.8 Commit and Push to GitHub ................................................................273 5.4.9 Create GitHub Release ........................................................................273 5.4.10 Recommended Project Structure .....................................................273 5.5 Summary.....................................................................................................273 Table of ConTenTs
xii Chapter 6: Building and Deploying a Simple Web Service ����������������275 6.1 Introduction .................................................................................................275 6.2 Introduction to Web Services ......................................................................276 6.2.1 What Is a Web Service? .....................................................................276 6.2.2 Typical Use Cases ..............................................................................276 6.2.3 Examples of Go-Based Web Services ................................................276 6.3 Understanding Open Source Web Projects .................................................277 6.3.1 Why Open Source Your Web API? ........................................................277 6.3.2 Quick Best Practices ..........................................................................277 6.4 Step by Step: Build and Release a URL Shortener API in Go .......................277 6.4.1 Problem Statement ............................................................................277 6.4.2 Set Up Project Structure .....................................................................278 6.4.3 Implement the Web Service ................................................................278 6.4.4 Add License and README ..................................................................282 6.4.5 Deploy Your Service ............................................................................283 6.4.6 Test Using Postman (Optional but Recommended) .............................284 6.4.7 Add Security and Persistence Notes...................................................284 6.4.8 Create GitHub Release ........................................................................285 6.5 Summary.....................................................................................................285 Appendix A: Golang Cheat Sheet ������������������������������������������������������287 Appendix B: Golang Best Practices (Top 20)�������������������������������������295 Appendix C: Golang Is Written in Go—How? ������������������������������������305 Index �������������������������������������������������������������������������������������������������311 Table of ConTenTs
xiii Rahul Sid Patil is a seasoned software engineer and thought leader with more than a decade of experience in Golang, cloud-native development, and distributed systems. As the Head of the Golang Community at EPAM Systems, India, he plays a pivotal role in fostering collaboration and innovation within the developer ecosystem. A dynamic public speaker, Rahul has shared his expertise at prestigious international tech events, including the Great Indian Developer Summit (GIDS). He has also served as a mentor and jury member at the Smart India Hackathon, one of the world’s largest hackathons, inspiring and guiding the next generation of tech talent. Rahul is a popular author on Medium, where he writes on software development and modern technology practices, and an open source contributor known for the “crongen” library. He is the founder of the Cloud Native Developer’s Forum (CNDF), a YouTube channel dedicated to educating developers on cloud-native technologies. About the Author
xv Pranav Manole is a seasoned web developer with experience in working with various web technologies. He's been working in the IT industry for more than 7.5 years. Currently, he is working as a Senior Software Engineer at Victoria’s Secret & Co., Bangalore. For the past four years, he has been actively working in Golang and exploring various aspects of it. He feels Golang, one of the most widely accepted languages, is very easy to learn. Due to its key features like concurrency, memory management, error handling, and most importantly simplicity, it is getting popular in the IT industry. He feels this book is written in such a way that the reader will find it engaging due to the question-and-answer structure. The what, why, where, and how of Golang concepts are explained in a systematic way.  About the Technical Reviewer
xvii Acknowledgments I would like to extend my heartfelt gratitude to the following people who have played a crucial role in making this book a reality: • Anandadeep Roy, editor (web development and open source), for giving me the opportunity to write this book and for his invaluable guidance throughout the process • Deepa Shirley Tryphosa, project coordinator for this book, for her patient follow-ups and insightful inputs that helped shape this work • Pranav Manole, Senior Software Engineer at Victoria’s Secret & Co., for his thorough and on-point technical review, ensuring the quality and accuracy of the content • My family—my wife Bhagyashree, my daughter Urvi, and my mother Nandini—for their unwavering support and understanding of my lack of availability for the family during this project Without their encouragement and dedication, this book would not have been possible.
xix Introduction Welcome to Let Us Go!, your practical guide to mastering Go programming! This book is designed to help you navigate the fundamentals of Go, a modern programming language that’s transforming the way developers build scalable, efficient, and high-performance applications. Whether you are A beginner programmer with little to no prior experience in Go but eager to learn with clear, step- by- step guidance A student seeking a comprehensive resource to supplement your coursework and apply programming concepts through hands-on projects A self-taught developer transitioning into professional Go development, looking for a structured approach and practical examples A hobbyist or enthusiast keen on exploring a new language and building projects you can showcase A professional developer aiming to upskill and leverage Go's capabilities for enterprise-level software this book is tailored to make your learning journey engaging, interactive, and rewarding.
xx Why Golang Is the Future of Enterprise Software Development In the fast-paced world of enterprise software development, efficiency, scalability, and maintainability are paramount. With modern businesses demanding robust, high-performance applications that can scale seamlessly in cloud environments, development teams are reevaluating their language choices. Enter Golang—a language that’s not just a tool but a game-changer. Here’s why enterprise software development companies are increasingly turning to Golang to build the future. The Rise of Golang: An Overview Developed by Google in 2007 and released to the public in 2009, Golang (or simply Go) was designed to address the challenges of modern software development. With a syntax reminiscent of C, combined with modern programming constructs, Golang was created to balance simplicity and power. Today, it's the language behind some of the most critical systems, including Kubernetes, Docker, and Prometheus. Why Enterprises Love Golang 1. Blazing Performance Without Complexity Compiled Language: Golang compiles directly to machine code, eliminating the overhead of runtime interpretation. This translates to faster execution times and better resource utilization. Optimized for Concurrency: In Go, a goroutine is a lightweight way to perform multiple tasks at the same time. Imagine cooking dinner while the washing machine is running—goroutines allow your program to InTroduCTIon
xxi handle such multitasking effortlessly. You’ll get hands-on experience with goroutines when we cover concurrency in later chapters. Garbage Collection: This is an automatic process that cleans up unused memory while your program is running. Think of it as a janitor that ensures your application runs smoothly without you having to manually manage memory. Don’t worry—we’ll dive deeper into how Go handles memory in later chapters. Note If you’re new to terms like “garbage collection” or “goroutines,” don’t worry! These concepts will be explained step by step with practical examples in later chapters. 2. Perfect for Cloud-Native Environments Built for Scalability: In the age of distributed systems, Golang’s concurrency model shines. Tools like Kubernetes, Docker, and Istio, all written in Go, leverage its capabilities to scale effortlessly in cloud environments. Cross-Platform Compatibility: Go makes it easy to build applications that work across various platforms. Its ability to produce static binaries simplifies deployment, especially in containerized environments. Standard Library for Networking: Go's robust standard library has built-in support for networking and HTTP servers, reducing the need for external dependencies and speeding up development. 3. Simplicity Equals Productivity Clean and Readable Syntax: Go was designed to reduce cognitive load. With a focus on simplicity, it eliminates features like inheritance and complex metaprogramming, making the code easier to read, write, and maintain. InTroduCTIon
xxii Short Learning Curve: For enterprises, onboarding new developers can be a challenge. Go’s simplicity enables developers, even those new to the language, to become productive quickly. Minimal Magic: Unlike languages that rely heavily on frameworks and hidden abstractions, Go's philosophy is “what you see is what you get.” This predictability makes debugging and optimization straightforward. 4. Cost Efficiency Fewer Resources, Greater Output: Thanks to Go’s efficient use of resources, enterprises can achieve more with fewer servers and reduced operational costs. Developer Productivity: Go’s emphasis on simplicity and tooling ensures that development teams spend less time on debugging and refactoring and more on delivering value. Open Source Ecosystem: Go's vibrant community and ecosystem mean enterprises can leverage a plethora of high- quality libraries and tools without additional costs. 5. Reliability and Maintainability Strong Typing: Go uses a system called static typing, which means you must define the type of each variable (like whether it holds a number or text) before you use it. This helps catch errors early and makes your code more reliable. We’ll explore Go’s type system in later chapters. Built-In Testing: Go includes a testing framework as part of its standard library, encouraging a test-driven development approach that improves software quality. Backward Compatibility: Go has committed to backward compatibility in its updates, ensuring that existing codebases remain functional and future-proof. InTroduCTIon
xxiii Use Cases Driving Golang Adoption 1. Microservices Architecture Golang’s lightweight binaries, rapid startup times, and support for gRPC make it an ideal choice for building scalable microservices architectures. 2. DevOps and Infrastructure Tools The very tools that power DevOps—like Kubernetes, Docker, and Terraform—are written in Go. Enterprises building custom DevOps solutions are naturally drawn to the language. 3. High-Performance APIs With its low latency and high concurrency capabilities, Go is widely used to build RESTful APIs and high-performance backend services for enterprises. 4. Real-Time Applications From chat systems to gaming platforms, Golang’s concurrency model is well suited for applications requiring real-time processing. 5. Big Data and Stream Processing For tasks like log aggregation, real-time data processing, and ETL pipelines, Go's speed and scalability make it a strong contender. InTroduCTIon