Go 语言是一种静态类型的编程语言,具有简洁、可靠、高效的特点。下面是 Go 语言的基础语法,包括变量、数据类型、控制结构、函数、字符串、数组和切片、指针、结构体、接口、错误处理和并发编程等。
Go 语言中,可以使用 var 语句声明变量。例如:
- var x int
- x = 10
也可以使用 short variable declarations 语句声明变量。例如:
x := 10
Go 语言中,还有许多内置的变量类型,例如 int、float、bool、string 等。
Go 语言中,有许多内置的数据类型,例如:
int:整数类型float:浮点数类型bool:布尔类型string:字符串类型byte:字节类型rune: Unicode 字符类型complex:复数类型imag:虚数类型Go 语言中,有以下几种控制结构:
if 语句:if x > 0 { ... }for 语句:for i := 0; i < 5; i++ { ... }switch 语句:switch x { case 1: ... case 2: ... }goto 语句:goto LABELGo 语言中,可以使用 func 语句声明函数。例如:
- func add(x int, y int) int {
- return x + y
- }
函数可以返回多个值,例如:
- func add(x int, y int) (int, int) {
- return x + y, x - y
- }
Go 语言中,可以使用 string 语句声明字符串。例如:
str := "hello world"
字符串可以使用 + 运算符连接,例如:
str := "hello " + "world"
字符串可以使用 fmt.Sprintf 函数格式化,例如:
str := fmt.Sprintf("hello %s", "world")
Go 语言中,可以使用 [] 语句声明数组和切片。例如:
arr := [5]int{1, 2, 3, 4, 5}
数组和切片可以使用索引访问,例如:
arr[0] = 10
数组和切片可以使用 len 函数获取长度,例如:
len(arr)
Go 语言中,可以使用 * 语句声明指针。例如:
p := &x
指针可以使用 * 运算符解引用,例如:
*p = 10
Go 语言中,可以使用 struct 语句声明结构体。例如:
- type Person struct {
- name string
- age int
- }
结构体可以使用点号访问字段,例如:
- p := Person{"John", 30}
- p.name = "Jane"
Go 语言中,可以使用 interface 语句声明接口。例如:
- type Printer interface {
- Print()
- }
接口可以实现多个方法,例如:
- type Logger struct{}
- func (l Logger) Print() {
- fmt.Println("log")
- }
Go 语言中,可以使用 error 语句声明错误。例如:
- type error interface {
- Error() string
- }
错误可以使用 if 语句处理,例如:
- if err != nil {
- fmt.Println(err)
- }
Go 语言中,可以使用 go 语句声明 goroutine。例如:
- go func() {
- fmt.Println("hello")
- }()
goroutine 可以使用 channel 语句通信,例如:
- ch := make(chan int)
- go func() {
- ch <- 10
- }()
goroutine 可以使用 sync 语句同步,例如
- mu := &sync.Mutex{}
- go func() {
- mu.Lock()
- fmt.Println("hello")
- mu.Unlock()
- }()