golang package provided by the system by running the following command, and then use it for Go development.dnf install -y golang
go version
go version go1.19 linux/amd64
wget https://go.dev/dl/go1.19.linux-amd64.tar.gz
/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/gosudo tar -C /usr/local -xzf go1.19.linux-amd64.tar.gz
PATH environment variable:export PATH=$PATH:/usr/local/go/bin
/etc/profile file:echo 'export PATH=$PATH:/usr/local/go/bin' | sudo tee -a /etc/profilesource /etc/profile
go version
go version go1.19 linux/amd64
go run command.touch hello.go to create a file, and add the following content:package mainimport "fmt"func main() {fmt.Println("Hello, TencentOS!")}
go run hello.go
Hello, TencentOS!
$HOME/go, create the project directory by running the following command:mkdir -p $HOME/go/{src,bin,pkg}
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.export GOPATH=$HOME/go
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_projectcd ${GOPATH}/src/my_project
main.go and add the following code:package mainimport ("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)}}
go mod init example.com/my_projectgo mod tidy
go build
go install command:go install
my_project will be generated in the bin directory and can be run directly:$HOME/go/bin/my_projectPerson 1: Sofia MartinPerson 2: Emily AndersonPerson 3: Elizabeth TaylorPerson 4: Emma MillerPerson 5: Isabella Smith
cd ~/gotree -L 3
.├── bin│ └── my_project├── pkg│ ├── mod│ │ ├── cache│ │ ├── github.com│ │ └── golang.org│ └── sumdb│ └── sum.golang.org└── src└── my_project├── go.mod├── go.sum└── main.go
fmt.Printlnfmt.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.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)
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()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.runtime/debug:import (..."runtime/debug"...)
...debug.PrintStack()...
pprof package:import (..."runtime/pprof"...)
pprof file, for example:f, err := os.Create("cpu.pprof")
pprof.StartCPUProfile() function is called to start recording the CPU configuration file:pprof.StartCPUProfile(f)
pprof.StopCPUProfile() function to stop recording the CPU configuration file.defer pprof.StopCPUProfile()
cpu.pprof file upon completion. Use the following command to enter the interactive interface for detailed analysis.go tool pprof cpu.pprof
File: mainType: cpuTime: 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) topShowing nodes accounting for 440ms, 100% of 440ms totalflat flat% sum% cum cum%440ms 100% 100% 440ms 100% main.fibonacci0 0% 100% 440ms 100% main.main0 0% 100% 440ms 100% runtime.main
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.go.mod that contains the module name of the project and the current Go version.go mod init <module-path>
go mod init example.com/my_projectcat go.mod
module example.com/my_projectgo 1.19
go.mod and go.sum files.go mod tidy
go.mod file:cat go.mod
module example.com/my_projectgo 1.19require github.com/Pallinder/go-randomdata v1.2.0require golang.org/x/text v0.9.0 // indirect
go.mod file and obtains the requested version.go get <dependency_path>@<version>
go get github.com/Pallinder/go-randomdata@v1.1.0cat go.mod
module example.com/my_projectgo 1.19require github.com/Pallinder/go-randomdata v1.1.0require golang.org/x/text v0.9.0 // indirect
go.mod file is updated.git commit, for example:go get github.com/Pallinder/go-randomdata@3e0fbf126b9e6853a5e50951913caab476d650c7
go: downloading github.com/Pallinder/go-randomdata v0.0.0-20181031200937-3e0fbf126b9ego: downgraded github.com/Pallinder/go-randomdata v1.2.0 => v0.0.0-20181031200937-3e0fbf126b9e
cat go.mod
module example.com/my_projectgo 1.19require github.com/Pallinder/go-randomdata v0.0.0-20181031200937-3e0fbf126b9erequire golang.org/x/text v0.9.0 // indirect
go list -u -m all
example.com/my_projectgithub.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.0golang.org/x/tools v0.6.0 [v0.9.1]
import (...// "github.com/Pallinder/go-randomdata"...)
go mod tidy
go list -u -m all
example.com/my_project
example.go with the following content, but note that the code layout and indentation are not standardized:package mainimport "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 fmt example.go
cat example.go
package mainimport "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)}}
example.go that contains an error: a mismatch between the placeholder and the argument in Printf:package mainimport "fmt"type Person struct {FirstName stringLastName stringAge 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)}
go vet reports the following error:go vet example.go
# command-line-arguments./example.go:18:2: fmt.Printf format %s reads arg #4, but call has 3 args
example.go has an extra argument but no corresponding formatting directive.go vet from the project root directory:go vet ./...
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.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)}
go mod init example.com/stringutilgo mod tidy
go doc example.com/stringutil
package stringutil // import "example.com/stringutil"Package stringutil contains utility functions for manipulating strings.func Reverse(s string) string
go doc example.com/stringutil.Reverse
package stringutil // import "example.com/stringutil"func Reverse(s string) stringReverse returns a reversed copy of the input string s.
Esta página foi útil?
Você também pode entrar em contato com a Equipe de vendas ou Enviar um tíquete em caso de ajuda.
comentários