
Go语言中的变量使用关键字 var 来声明,例如 var x int = 10。Go语言也支持简化的赋值语法,例如 x := 10。
Go语言的类型系统非常严格,编译器会在编译阶段检查类型的正确性,这使得Go语言的代码更安全和可靠。Go语言的类型系统还支持多重赋值,例如 x, y := 10, 20。
Go语言的函数可以使用关键字 func 来声明,例如 func add(a, b int) int { return a + b }。Go语言的函数也支持多参数和返回值。
Readers also liked: Go vs Golang
Getting Started
To get started with Go, you need to know that a Go program is made up of packages. The main package is special because it tells the compiler that the program can be compiled into an executable file, rather than a shared library, and it serves as the application's entry point.
The main package is defined in a specific format, and you can create a simple "hello world" example by creating a file called main.go in your Go workspace.
To store a sequence of bytes, Go uses the string type, which is declared with the keyword string.
Explore further: Create a Package in Golang
Prerequisites
Getting started with programming can be intimidating, but don't worry, I've got you covered. You'll need some basic programming experience to follow along, so if you're new to coding, you might want to start with some beginner-friendly tutorials.
To write and edit your code, you'll need a tool that can handle text editing. Fortunately, most text editors have good support for Go, and some popular options include VSCode, GoLand, and Vim.
If you're on a Linux or Mac machine, you can use any terminal you have, but if you're on Windows, you'll need to use PowerShell or cmd.
Check this out: Golang Use .env File
Install
To get started, you'll need to install Go. Just use the Download and install steps.

The downloaded packages are saved in the environment variable env's GOPATH directory, which is your workspace. You can view the downloaded packages by going to the pkg folder within your workspace directory, cd $GOPATH/pkg.
The installation process is straightforward, and you'll be up and running with a "Hello, World" example in no time.
Create Custom Package
To create a custom package, start by making a file folder with the same name as your package, such as "person" for a package named "person".
Create a new file called "person.go" inside this folder, where you can define the methods and functions for your package.
You'll need to install your package so it can be imported and used elsewhere, which you can do by running the installation command.
Now that your package is installed, you can create a new file called "main.go" inside the same folder to test and use your custom package.
When you create methods in your package, remember that those starting with a lowercase letter are private and can't be accessed from outside the package, like the "secretName" method in the example.
A unique perspective: Golang Go
Introduction

To get started with Go, you need to understand that it's composed of packages. The main package, in particular, tells the compiler that your program can be compiled into an executable file, rather than a shared library, and it serves as the entry point for your application.
The main package is defined in a specific format, which we'll explore further in our examples.
Go programs are typically stored in files with a .go extension, and the first step is to create a file called main.go in your Go workspace.
In Go, strings are used to store a sequence of bytes, and they're declared using the string keyword.
The Go compiler looks for the main package to determine the entry point of your program, and it's essential to have a main package in your Go program.
For your interest: Install Golang Package
Basic Syntax
Go 语言的变量类型定义包括全局变量、局部变量、多变量和零值。例如,在 lesson3 中,我们可以看到 Go 语言的变量类型定义是通过关键字来实现的。
Go 语言的基本运算符包括加法、减法、乘法、除法、等等。例如,在 lesson5 中,我们可以看到 Go 语言的运算符包括 +、-、*、/ 等。
这些是 Go 语言的基本语法,了解它们可以帮助我们更好地编写 Go 语言的代码。
Write Some Code

To write some code in Go, you'll need to create a new directory for your project. You can do this by opening a command prompt and navigating to your home directory. On Linux or Mac, you can do this with the command `cd`, while on Windows, you can use `cd %HOMEPATH%`.
Once you've created a new directory, you can enable dependency tracking for your code by running the `go mod init` command. This will create a new `go.mod` file that tracks the dependencies for your project. For example, if you want to create a new module called `example/hello`, you can run the command `go mod init example/hello`.
Next, you'll need to create a new file called `hello.go` where you'll write your Go code. In this file, you can use the `fmt` package to print out a greeting to the console. For example, you can use the following code:
```go
package main
Here's an interesting read: Golang Test Command

import "fmt"
func main() {
fmt.Println("Hello, World!")
}
```
To run your code, you can use the `go run` command. This will compile and run your code in one step. Alternatively, you can use the `go build` command to compile your code into a standalone executable, and then run it with the `./main` command.
Here are some basic Go commands to get you started:
- `go mod init`: Initializes a new Go module
- `go run`: Compiles and runs Go code
- `go build`: Compiles Go code into a standalone executable
- `go help`: Displays a list of available Go commands
关键字
In Go, there are 25 keywords or reserved words that are used in code. These keywords include break, default, func, interface, select, and many others.
Here's a breakdown of the keywords in Go:
In addition to these 25 keywords, Go has 36 predefined identifiers that are used in the language.
语言的空格
Language has a unique way of creating spaces, or "空格" in Chinese, that can completely change the meaning of a sentence. This is a fundamental concept in basic syntax.
A simple example is the word "book" - without any context, it's just a noun. But add a verb like "read" and it becomes "read a book", changing the entire sentence. This is what we mean by "语言的空格".
Related reading: Golang Read Image File

In many languages, including English, this concept is often referred to as a "gap" or a "space" between words. It's a subtle but powerful tool that can make or break the meaning of a sentence. This is why understanding the syntax of language is so important.
For instance, the sentence "I love my mother" and "I love my mother's cooking" have the same words, but the "空格" between "love" and "my mother" changes the entire meaning of the sentence. This is a fundamental aspect of language that we need to grasp.
Control Flow
Control Flow is a fundamental concept in programming, and Go has its own unique way of handling it.
Switch cases are helpful in organizing multiple condition statements, as shown in a simple switch case statement: "switch case / Switch cases 有助于组织多个条件语句。 以下示例显示了一个简单的 switch case 语句:"
Loops, on the other hand, are used when you need to execute a block of code repeatedly. Go provides a for keyword for this purpose, which can be used to implement different types of loops.
A single for loop command can help achieve various types of loops, similar to a while loop in C. For example, an infinite loop can be created using the for loop command, just like in the Go example: "Go 中的无限循环:"
For more insights, see: Golang Use Cases
Control Flow
Control Flow is a fundamental concept in programming that allows you to control the flow of your code.
Switch case statements help organize multiple conditional statements.
In Go, you can use a simple switch case statement to achieve this, as shown in the example: "switch case".
A switch case statement is particularly useful when dealing with multiple conditions.
The Go language also provides a loop keyword, making it easier to implement different types of loops.
A single for loop command can be used to achieve various types of loops, similar to a while loop in C.
The for loop command is versatile and can be used for different types of loops.
In Go, you can use the same for statement for both for and while loops.
Switch case statements and loops are essential tools in your programming toolbox, allowing you to write more efficient and organized code.
See what others are reading: Golang Code Comment Specifications
Defer
Defer is a function that executes at the end of a program, allowing you to perform certain actions after the main execution is complete.
It's particularly useful for closing files or executing other cleanup tasks that need to happen after the program finishes running.
In the example, a panic() function was used to execute the program, and a defer statement was used to make sure a certain line of code is executed at the end.
You can use Defer to close files or perform other cleanup tasks that need to happen after the program finishes running.
Defer statements can be used in functions to ensure that certain tasks are completed before the function ends.
In the example, the defer statement ensured that the program executed a certain line of code after the main execution was complete.
For another approach, see: Golang Source Code
Work Space
Working with a Go workspace is essential to managing your code. The workspace is defined by the GOPATH environment variable.
The GOPATH variable tells Go where to look for packages. You can set GOPATH to any directory you like, and I've set mine to ~/workspace.
Explore further: Golang Set Env Variable

To create a new workspace, you'll need to set GOPATH to a specific directory. For example, you could set it to ~/workspace.
In Go, the GOPATH directory is where all your code will be written. Go will search for packages in the GOPATH directory, or in the GOROOT directory, which is set by default when you install Go.
You can create a new file called main.go in your workspace directory. For instance, I created a file called main.go in ~/workspace.
The GOPATH directory is where Go will look for packages. You can use the GOPATH directory to organize your code and make it easier to find what you need.
Explore further: Golang Test Main
Functions and Methods
Functions in Go are defined using the func keyword, and can be used to perform a specific task.
You can define a function within the main package, which is the entry point of your program. For example, you can define a function like this:
You might enjoy: Golang Function Type
func main() {}
Functions can also have a return value, which can be defined within the function itself. This means you don't need to use the return statement to define the return value.
You can return multiple values from a single function, by separating them with a comma. For example:
func main() (c) {}
Methods in Go are a special type of function that can be used with a specific data type. They can return a value, or a pointer to a value.
Methods are defined using the same syntax as functions, but with a receiver parameter. For example, you can define a method like this:
func (p person) describe() {}
Arrays, Slices, and Maps
Arrays in Go are defined by specifying a fixed length, which means they cannot be expanded. You can create a multi-dimensional array using a specific format.
Arrays are not suitable for situations where the values need to be changed at runtime. For this purpose, Go has a data type called slices.
Slices are a collection of elements that can be expanded or shrunk dynamically. They are declared similarly to arrays, but without specifying the length. A slice can be created with zero capacity and length.
A slice can be defined with an initial length and capacity. The initial length is the number of elements it can hold, while the capacity is the total number of elements it can store.
A slice is an abstraction of an array. It uses an array as its underlying structure and consists of three components: capacity, length, and a pointer to the underlying array.
You can increase a slice's capacity by using the append or copy function. The append function adds elements to the end of the array and increases the capacity if necessary.
Another way to increase a slice's capacity is by using the copy function. You can create a new slice with a larger capacity and copy the original slice into it.
Slices can be created as a subset of another slice. This can be done using the following command.
Worth a look: Golang Copy Array
类型转化
在 Python 中,类型转化是通过使用内置函数来实现的,如 int()、float()、str() 等。这些函数可以将不同类型的值转换为指定类型。
例如,使用 int() 函数可以将字符串转换为整数,如 int("123")。同样,使用 float() 函数可以将字符串转换为浮点数,如 float("123.45")。
类型转化在数据处理和分析中非常重要,例如在处理用户输入数据时需要将字符串转换为数字类型,以便进行数学运算。
Function
Functions in Go are defined using the func keyword followed by the function name. You can define and use more functions within the main function, which is defined in the main package and serves as the program's entry point.
You can define variables before the return statement to automatically return them, as seen in the example where variable c is defined and returned without needing a separate return statement.
Functions can also return multiple values, separated by commas, allowing you to handle multiple return values in a single function call.
The main function is the entry point of a Go program, where you can define and use additional functions.
Methods
Methods are a special type of function that return values, which can be either values or pointers.
In Go, methods are used to modify existing objects, and they can return the modified object. For example, the describe method returns a pointer to a person struct, allowing you to modify the returned object and see the changes reflected in the original object.
Using pointers as return values also saves memory by not creating a new copy of the object. This is demonstrated in the example where the age of a person is modified, but the name remains unchanged because the setName method returns a value, while the setAge method returns a pointer.
Methods can be used to add functionality to existing types, making them more useful and versatile. By using methods, you can create more robust and maintainable code.
Worth a look: How to Update a Github Using Golang
实例
In Python, functions and methods are used to encapsulate reusable code. A function can be called multiple times in a program without having to rewrite the code.
The math.sqrt() function is a built-in function that calculates the square root of a number. It can be used to find the length of a side of a square given its area.
Functions can also be defined by the user, such as the greet() function that prints a greeting message. This function can be called multiple times in a program to print the greeting message.
The greet() function takes one argument, the name of the person to be greeted. This allows the function to be flexible and reusable in different contexts.
You might enjoy: Golang Message
Error Handling
Error handling is a crucial aspect of Go programming.
In Go, errors are unexpected results that a program does not want to occur.
When making API calls, errors can happen, and Go can identify these errors in the program.
You can check if an error object exists and handle the response accordingly.
The error object may or may not exist, depending on the API call's success or failure.
It's essential to handle errors in a program, and Go has a built-in mechanism for this.
When writing your own functions, you can return custom errors using the error object.
These errors should never be ignored and should be handled elegantly where the function is called.
You might like: Gcloud Api Using Golang
Concurrency
Concurrency is a fundamental concept in Go programming. Go routines are lightweight threads that can run concurrently with the main thread, and creating them is as simple as adding the keyword "Go" before a function.
You can create a Go routine by adding the keyword "Go" before a function, as shown in the example where function "c" is a Go routine running concurrently with the main thread. This allows for thousands of routines to be created.
To share resources between Go routines, Go uses channels instead of sharing variables between threads, which can lead to deadlocks and resource waiting. Channels are created by specifying the data type they will receive, as shown in the example of a string-type channel.
Channels can be used to send and receive data between Go routines, with the receiving channel waiting for data to be sent. You can create a channel by using the "chan" keyword followed by the data type, like "chan string".
You can also create single-direction channels, where a Go routine can only send or receive data but not both, as shown in the example where "sc" is a Go routine that can only send messages to the channel.
To handle multiple channels in a single Go routine, you can use the "select" statement, which allows you to specify multiple channels to listen for data on, as shown in the example where the main method uses "select" to listen for data on channels "c1" and "c2".
In some cases, you may need to send multiple data to a channel, which can be achieved by creating a buffered channel. A buffered channel allows data to be sent to the channel without blocking, up to the buffer size.
Curious to learn more? Check out: Golang Channels
Standard Library
The Go standard library is a treasure trove of useful packages that make your life as a developer easier.
The fmt package is a great example of this, providing formatted I/O functionality that lets you print to the standard output with ease.
Another incredibly useful package is the json package, which enables you to encode and decode JSON data with a few simple lines of code. In fact, the json package can even map JSON keys to specific fields in your structs, like how "page" gets mapped to PageNumber in the example.
Worth a look: Golang Read Json File
Standard Library
The Go standard library is packed with useful packages that can simplify your development process.
The fmt package is a great place to start, as it allows you to format I/O operations with ease. You can use it to print to the standard output with just a few lines of code.
The json package is another essential tool in the Go standard library, enabling you to encode and decode JSON data with precision. To illustrate this, let's take a look at how you can encode and decode JSON data using the unmarshal function.
To unmarshal JSON bytes, you need to pass in the JSON bytes as the first argument and a pointer to the struct you want to map the JSON to as the second argument.
Broaden your view: Convert a Map to Json Golang
Installation of Packages

You can install packages in the environment variable env's GOPATH directory, which is your working directory.
The installed packages are saved in the GOPATH directory, making it easy to manage your dependencies.
You can view the downloaded packages by navigating to the pkg folder in your working directory, specifically in the GOPATH/pkg directory.
This directory structure is designed to keep your packages organized and easily accessible.
The GOPATH directory is where all your package installations will be saved, so keep it tidy!
Package Document
The Go standard library has a built-in package document support feature.
You can generate documentation for your packages using a simple command. This will create a document for the Description function inside your person package.
To view the generated documentation, you can start a web server using a specific command.
Broaden your view: Golang Command Line Arguments
Code Style and Tools
In Go, we use the Go fmt tool to format our code. This tool helps maintain a consistent coding style throughout the project.
Go has a built-in linter called golint, which checks our code for common errors and suggests improvements. It's a great tool to catch mistakes early on.
The Go community also uses third-party tools like gometalinter and go vet to further improve our code quality. These tools can be integrated into our development workflow to ensure our code is always up to date and follows best practices.
代码规范
使用空格和缩进来美化代码是很重要的。例如,在 Python 中,使用 4 个空格来缩进函数和循环体是常见的。同样,在 Java 中,使用 4 个空格或 1 个制表符来缩进也是推荐的。
一致的命名约定可以提高代码的可读性。例如,在 JavaScript 中,使用 camelCase 来命名变量和函数是常见的。例如,变量名 `firstName` 和函数名 `getUserName()` 是很好的实践。
代码注释是理解代码逻辑的关键。例如,在 Python 中,使用 `#` 符号来添加注释是很常见的。例如,`# 这是注释的例子` 可以帮助其他开发者理解代码逻辑。
Environment and Tools
Code editors like Visual Studio Code and Sublime Text are popular choices for developers due to their high performance and feature-rich interfaces.
The choice of code editor can greatly impact a developer's productivity, which is why many prefer these two options.
Code completion and auto-formatting features in Visual Studio Code can save a significant amount of time when writing code.

Auto-formatting, in particular, helps maintain a consistent code style throughout a project.
Sublime Text's advanced search and replace functionality is a game-changer for large codebases.
This feature allows developers to quickly locate and replace specific code patterns, streamlining the debugging process.
Code linting tools like ESLint and Prettier help catch errors and enforce coding standards.
Prettier's ability to format code according to a set of predefined rules is particularly useful for maintaining a consistent code style.
ESLint's customizable rules ensure that code adheres to specific coding standards and best practices.
外文翻译
GitHub has a popular Go cheat sheet in Chinese, which is a great resource for developers.
The official Go blog has published several articles about Go's 13th anniversary, highlighting the language's growth and evolution.
Go's developer survey revealed that the way developers work has changed, with a greater emphasis on collaboration and community involvement.
The official Go blog has also discussed the use of generics in Go, including scenarios where they are particularly useful.
Go's workspace pattern is a best practice that can help improve code organization and maintainability.
Go 1.18 has been released, bringing new features and improvements to the language.
The official Go tutorial on fuzzing testing provides a hands-on guide to this important testing technique.
Advanced Topics
In Go, you can use goroutines to run functions concurrently. This is a fundamental concept in Go that allows your program to perform multiple tasks simultaneously.
Go's concurrency model is based on the concept of goroutines, which are lightweight threads that can run concurrently. This makes it easy to write concurrent code that takes advantage of multiple CPU cores.
Using goroutines can significantly improve the performance of your program by allowing it to utilize all available CPU cores. For example, you can use goroutines to make multiple HTTP requests concurrently.
Go's select statement is used to choose which channel to send or receive data from. This is a powerful tool for handling concurrent operations.
The select statement is similar to a switch statement, but it's specifically designed for working with channels. It allows you to specify multiple channels and choose which one to send or receive data from based on certain conditions.
A unique perspective: How to Run a Golang Program
Go's WaitGroup type is used to wait for a group of goroutines to finish. This is a useful tool for ensuring that all goroutines have completed before your program continues.
A WaitGroup is essentially a counter that you can decrement when a goroutine finishes. When the counter reaches zero, the WaitGroup will unblock and your program can continue.
Go's sync package provides several synchronization primitives that can be used to coordinate access to shared resources. This is essential for writing concurrent code that's safe and efficient.
Some common synchronization primitives include Mutexes, RWMutexes, and Semaphores. These can be used to protect shared resources, ensure exclusive access, and manage access to shared resources.
Databases and APIs
In Go, databases and APIs are crucial for storing and retrieving data.
Go provides several packages for interacting with databases, including the database/sql package, which allows you to connect to different types of databases.
To connect to a database, you need to import the database/sql package and the driver package for the specific database you're using, such as mysql or postgres.
The database/sql package provides a standard interface for interacting with databases, making it easy to switch between different databases.
Databases
Databases are a crucial part of any API, allowing developers to store and manage data efficiently.
A database is essentially a collection of organized data that can be easily accessed and manipulated.
Relational databases, like MySQL, use tables to store data in a structured format.
NoSQL databases, on the other hand, use a variety of data models, such as key-value pairs or documents, to store data.
Database normalization is a process that helps prevent data redundancy and improves data integrity by breaking down large tables into smaller ones.
This is particularly important for large datasets, where data duplication can lead to inconsistencies and errors.
APIs often interact with databases using queries, which are requests for specific data or operations.
The choice of database depends on the specific needs of the project, with relational databases being suitable for structured data and NoSQL databases for unstructured or semi-structured data.
Swagger
Swagger is an open-source framework that allows developers to describe, produce, and consume RESTful APIs. It's used to define the API's structure, including the data types, methods, and parameters.
APIs are the backbone of modern web development, and Swagger makes it easy to create and maintain them. This framework is particularly useful for documenting APIs, making it easier for other developers to understand and use them.
One of the key features of Swagger is its ability to automatically generate API documentation. This means that developers can focus on writing code, while Swagger takes care of creating the documentation.
Featured Images: pexels.com


