Resolving common doubts about getting started with Go programming: Install Go through brew, apt or choco and check the version; write a hello world program and run it; use the var keyword or abbreviation to define variables; Go supports data types such as integers, floating point numbers and Boolean; Functions are reusable blocks of code that perform specific tasks; errors can be represented by errors of type variables and returned when errors occur.
# macOS brew install go # Linux sudo apt install golang-go # Windows choco install golang
Use go version
to check whether the installation is successful.
Create file hello.go
:
package main import "fmt" func main() { fmt.Println("你好,世界!") }
Run program:
go run hello.go
Use var
Keyword:
var name string = "小明"
or abbreviation:
name := "小美"
Go supports various data types:
// 整数类型 var age int = 18 // 浮点数类型 var weight float64 = 60.5 // 布尔类型 var isMale bool = true
A function is a set of reusable blocks of code used to perform a specific task.
func average(numbers []int) float64 { var sum float64 for _, number := range numbers { sum += float64(number) } return sum / float64(len(numbers)) }
You can use variables of type error
to represent errors:
func divide(x, y int) (int, error) { if y == 0 { return 0, errors.New("除数不能为0") } return x / y, nil }
Calculate the average of two numbers
// main.go package main import "fmt" func average(numbers []int) float64 { var sum float64 for _, number := range numbers { sum += float64(number) } return sum / float64(len(numbers)) } func main() { numbers := []int{1, 2, 3, 4, 5} avg := average(numbers) fmt.Printf("平均值为:%.2f\n", avg) }
Running the program will output:
平均值为:3.00
The above is the detailed content of A guide to clearing up common doubts about getting started with Golang: Xiaobai's gospel. For more information, please follow other related articles on the PHP Chinese website!