tencent cloud

TencentOS Server

Go Development Guide

Baixar
Modo Foco
Tamanho da Fonte
Última atualização: 2026-10-19 17:22:50
Traduzido por IA

Introduction to Go

Go (Golang) is an open-source programming language launched by Google that is compiled, statically typed, highly concurrent, and garbage-collected. It is simple, efficient, and offers strong concurrency support, and is widely used in cloud computing, Web development, and network programming.

Go Installation

Installing with dnf

You can directly install the golang package provided by the system by running the following command, and then use it for Go development.
dnf install -y golang
After installation, run the following command to confirm the installed version:
go version
Output example:
go version go1.19 linux/amd64

Custom Installation

If you need a custom installation, refer to the following steps to use the official binary files:
1. Download the official binary files. This example installs Go 1.19, and you can download other versions as needed:
wget https://go.dev/dl/go1.19.linux-amd64.tar.gz
2. Extract the downloaded tarball to the /usr/local directory. If an older version of Go already exists on the system, delete the /usr/local/go directory first:
sudo rm -rf /usr/local/go
sudo tar -C /usr/local -xzf go1.19.linux-amd64.tar.gz
3. Add the Go executable file directory to the PATH environment variable:
export PATH=$PATH:/usr/local/go/bin
To make the configuration take effect permanently for all users, write it to the /etc/profile file:
echo 'export PATH=$PATH:/usr/local/go/bin' | sudo tee -a /etc/profile
source /etc/profile
4. Verify whether Go is installed successfully:
go version
Output example:
go version go1.19 linux/amd64

Using Go

Running Go Directly

A Go program can be run directly by using the go run command.
Run touch hello.go to create a file, and add the following content:
package main

import "fmt"

func main() {
fmt.Println("Hello, TencentOS!")
}
You can run this code directly.
go run hello.go
Output example:
Hello, TencentOS!

Creating a Go Project

For complex Go code involving dependencies, you can develop it by creating a Go project.
1. Assuming your project directory is $HOME/go, create the project directory by running the following command:
mkdir -p $HOME/go/{src,bin,pkg}
Among them:
src: the directory that contains source code files.
bin: the directory that contains executable files.
pkg: the directory that contains object files of compiled package dependencies.
2. Set the environment variable:
export GOPATH=$HOME/go
3. Initialize a new Go project named my_project for randomly generating names. Run the following command to create the project and go to the project directory:
mkdir -p ${GOPATH}/src/my_project
cd ${GOPATH}/src/my_project
4. Create a file named main.go and add the following code:
package main

import (
"fmt"

"github.com/Pallinder/go-randomdata"
)

func main() {
for i := 1; i <= 5; i++ {
randomName := randomdata.FirstName(randomdata.RandomGender) + " " + randomdata.LastName()
fmt.Printf("Person %d: %s\\n", i, randomName)
}
}
5. Initialize the Go module and install dependencies:
go mod init example.com/my_project
go mod tidy
6. Compile the project:
go build
7. Install the executable file by running the go install command:
go install
At this point, an executable file named my_project will be generated in the bin directory and can be run directly:
$HOME/go/bin/my_project
Person 1: Sofia Martin
Person 2: Emily Anderson
Person 3: Elizabeth Taylor
Person 4: Emma Miller
Person 5: Isabella Smith
At this point, a complete Go project directory tree looks like this:
cd ~/go
tree -L 3
Output example:
.
├── bin
│ └── my_project
├── pkg
│ ├── mod
│ │ ├── cache
│ │ ├── github.com
│ │ └── golang.org
│ └── sumdb
│ └── sum.golang.org
└── src
└── my_project
├── go.mod
├── go.sum
└── main.go

Debugging Features

fmt.Println

During development, printing variable values and the execution status at certain points in a program is the simplest and most common debugging method. You can use Go's fmt.Println() to output debugging information in the program.
Println consists of two parts: Print and ln (line). It indicates that a newline character is automatically added after printing is completed.
You can pass any number and type of arguments to fmt.Println. When output is performed, arguments are separated by spaces. Example:
fmt.Println("Hello, TencentOS!")
fmt.Println("The value is:", 42)
fmt.Println("Name:", "John", "Age:", 30)
The fmt.Println function is used to print values but does not support formatted string output. To output strings, use the fmt.Printf (or fmt.Sprintf) function. These functions provide more formatting options, such as placeholders (%d, %f, %s, and so on) and output control features (such as field width, precision, and padding characters).

debug.PrintStack()

The debug.PrintStack() function can throw the current program's stack to standard error output as text. To use this tool, you need to modify the code appropriately.
First, import runtime/debug:
import (
...
"runtime/debug"
...
)
Then add the following code where you need to print the call stack:
...
debug.PrintStack()
...
Run the modified code to print the call stack.

pprof

pprof is a visualization and debugging tool for Go that focuses on performance data analysis. To use this tool, you need to modify the code appropriately.
First, import the pprof package:
import (
...
"runtime/pprof"
...
)
Next, create a pprof file, for example:
f, err := os.Create("cpu.pprof")
Then, the pprof.StartCPUProfile() function is called to start recording the CPU configuration file:
pprof.StartCPUProfile(f)
After running the program for a period of time, use the pprof.StopCPUProfile() function to stop recording the CPU configuration file.
defer pprof.StopCPUProfile()
After this configuration, the program generates the cpu.pprof file upon completion. Use the following command to enter the interactive interface for detailed analysis.
go tool pprof cpu.pprof
Output example:
File: main
Type: cpu
Time: May 29, 2023 at 7:17pm (CST)
Duration: 609.33ms, Total samples = 440ms (72.21%)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) top
Showing nodes accounting for 440ms, 100% of 440ms total
flat flat% sum% cum cum%
440ms 100% 100% 440ms 100% main.fibonacci
0 0% 100% 440ms 100% main.main
0 0% 100% 440ms 100% runtime.main

Go Package Management

In addition to using the system-provided dnf command to manage Go-related packages, you can also use the Go Modules package management system provided by Go to handle projects and their dependencies.

Initializing Go Modules

To enable Go Modules in a project, run the following command in the project root directory. This command creates a file named go.mod that contains the module name of the project and the current Go version.
go mod init <module-path>
For example, the command used to create the project above:
go mod init example.com/my_project
cat go.mod
Output example:
module example.com/my_project

go 1.19

Installing and Updating Dependencies

To add or update dependencies, use the following command. This command downloads the missing dependencies and updates the go.mod and go.sum files.
go mod tidy
After the above command is executed, the dependent packages are added to the go.mod file:
cat go.mod
Output example:
module example.com/my_project

go 1.19

require github.com/Pallinder/go-randomdata v1.2.0

require golang.org/x/text v0.9.0 // indirect
To obtain a specific version of a dependency, use the following command. This command updates the go.mod file and obtains the requested version.
go get <dependency_path>@<version>
To use go-randomdata v1.1.0, run the following command:
go get github.com/Pallinder/go-randomdata@v1.1.0
cat go.mod
Output example:
module example.com/my_project

go 1.19

require github.com/Pallinder/go-randomdata v1.1.0

require golang.org/x/text v0.9.0 // indirect
At this point, the go.mod file is updated.
Alternatively, you can use a specific git commit, for example:
go get github.com/Pallinder/go-randomdata@3e0fbf126b9e6853a5e50951913caab476d650c7
Output example:
go: downloading github.com/Pallinder/go-randomdata v0.0.0-20181031200937-3e0fbf126b9e
go: downgraded github.com/Pallinder/go-randomdata v1.2.0 => v0.0.0-20181031200937-3e0fbf126b9e
cat go.mod
Output example:
module example.com/my_project

go 1.19

require github.com/Pallinder/go-randomdata v0.0.0-20181031200937-3e0fbf126b9e

require golang.org/x/text v0.9.0 // indirect

Viewing Current Dependencies and Their Details

To view information about all dependencies in the current project and their available updates, run the following command:
go list -u -m all
Output example:
example.com/my_project
github.com/Pallinder/go-randomdata v0.0.0-20181031200937-3e0fbf126b9e [v1.2.0]
golang.org/x/mod v0.8.0 [v0.10.0]
golang.org/x/sys v0.5.0 [v0.8.0]
golang.org/x/text v0.9.0
golang.org/x/tools v0.6.0 [v0.9.1]

Removing Unused Dependencies

To remove dependencies that are no longer used, first comment out the unused dependency packages in the source code:
import (
...
// "github.com/Pallinder/go-randomdata"
...
)
Then run the following command:
go mod tidy
At this point, the removed dependency is no longer listed:
go list -u -m all
Output example:
example.com/my_project

Introduction to Go Tools

go fmt

The go fmt command automatically formats Go source code files to ensure consistent code style and compliance with official coding standards.
For example, create a file named example.go with the following content, but note that the code layout and indentation are not standardized:
package main

import "fmt"

func main() {
fmt.Println("Hello, world!")
list:=[]int{9,7,5,3}
for i, val := range list {
fmt.Printf("Index: %d, Value: %d\\n",i,val)
}
}
Execute the following command:
go fmt example.go
After execution, the code is standardized:
cat example.go
Output example:
package main

import "fmt"

func main() {
fmt.Println("Hello, world!")
list := []int{9, 7, 5, 3}
for i, val := range list {
fmt.Printf("Index: %d, Value: %d\\n", i, val)
}
}

go vet

The go vet command statically checks Go source code for potential errors or suspicious coding patterns.
Create a file named example.go that contains an error: a mismatch between the placeholder and the argument in Printf:
package main

import "fmt"

type Person struct {
FirstName string
LastName string
Age int
}

func main() {
p := Person{
FirstName: "John",
LastName: "Doe",
Age: 30,
}

fmt.Printf("Person: %s %s, age %d, and an extra parameter: %s\\n", p.FirstName, p.LastName, p.Age)
}
After you run this command, go vet reports the following error:
go vet example.go
Output example:
# command-line-arguments
./example.go:18:2: fmt.Printf format %s reads arg #4, but call has 3 args
The tool indicates that line 18 of the file example.go has an extra argument but no corresponding formatting directive.
To check all Go code files in the entire project, including subdirectories, rather than only a single file, run go vet from the project root directory:
go vet ./...

go doc

The go doc command extracts documentation comments for packages, types, functions, and methods from Go source code and outputs them to the terminal in a readable plain text format.
For example, create a simple string utility library named stringutil.go:
// Package stringutil contains utility functions for manipulating strings.
package stringutil

// Reverse returns a reversed copy of the input string s.
func Reverse(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
Import and use the custom stringutil package:
go mod init example.com/stringutil
go mod tidy
After completing the preceding configuration, you can output the package description:
go doc example.com/stringutil
Output example:
package stringutil // import "example.com/stringutil"

Package stringutil contains utility functions for manipulating strings.

func Reverse(s string) string
You can also query the description of a function:
go doc example.com/stringutil.Reverse
Output example:
package stringutil // import "example.com/stringutil"

func Reverse(s string) string
Reverse returns a reversed copy of the input string s.


Ajuda e Suporte

Esta página foi útil?

comentários