综述由AI生成总结了 Go 语言的基础知识,涵盖环境搭建、基本语法(变量、常量、数据类型)、控制流(条件、循环、跳转)、集合操作(数组、切片、Map)、函数定义、面向对象特性(结构体、接口)、错误处理机制以及包管理和依赖管理。重点介绍了 Go 的并发编程模型,包括 Goroutine、Channel、Mutex、WaitGroup 及 Context 的使用,并提供了相应的代码示例和最佳实践建议。
在该目录下执行 go run hello.go ZYF,运行结果为 Hello World ZYF。
(二)基本程序结构编写学习
1. 变量
前提:chapter2 目录下创建 variables,学习总结如下:
变量声明:使用 var 关键字声明一个变量,例如:var x int。
类型推断:可以使用 := 操作符进行变量声明和赋值,Go 会根据右侧的值自动推断变量类型。
变量赋值:使用赋值操作符 = 给变量赋值。
多变量声明:可以同时声明多个变量。
零值:未初始化的变量会被赋予零值。
新建 fib_test.go,简单实用斐波那契数列进行练习:
package variables
import"testing"funcTestFibList(t *testing.T) {
a := 1
b := 1
t.Log(a)
for i := 0; i < 5; i++ {
t.Log(" ", b)
tmp := a
a = b
b = tmp + a
}
}
funcTestExchange(t *testing.T) {
a := 1
b := 2
a, b = b, a
t.Log(a, b)
}
package main
import"fmt"type Person struct {
FirstName string
LastName string
Age int
}
type Shape interface {
Area() float64
}
type Circle struct {
Radius float64
}
func(c Circle) Area() float64 {
return3.14 * c.Radius * c.Radius
}
funcadd(a, b int)int {
return a + b
}
type Operation func(int, int)intfuncmain() {
// 演示多种数据类型
fmt.Println("整数类型")
var x int = 10var y int64 = 100
fmt.Println(x, y)
fmt.Println("浮点数类型")
var a float32 = 3.14var b float64 = 3.14159265359
fmt.Println(a, b)
fmt.Println("布尔类型")
var isTrue bool = true
fmt.Println(isTrue)
fmt.Println("字符串类型")
str1 := "Hello, "
str2 := "Go!"
concatenated := str1 + str2
fmt.Println(concatenated)
fmt.Println("切片类型")
numbers := []int{1, 2, 3, 4, 5}
fmt.Println(numbers)
fmt.Println("映射类型")
ages := map[string]int{
"Alice": 25,
"Bob": 30,
}
fmt.Println(ages)
fmt.Println("结构体类型")
person := Person{
FirstName: "John",
LastName: "Doe",
Age: 30,
}
fmt.Println(person)
fmt.Println("接口类型")
var shape Shape
circle := Circle{Radius: 5}
shape = circle
fmt.Println("Circle Area:", shape.Area())
fmt.Println("函数类型")
var op Operation
op = add
result := op(10, 5)
fmt.Println("Addition:", result)
fmt.Println("通道类型")
messages := make(chanstring)
gofunc() {
messages <- "Hello, Go!"
}()
msg := <-messages
fmt.Println(msg)
fmt.Println("指针类型")
x = 10var ptr *int
ptr = &x
fmt.Println("Value of x:", x)
fmt.Println("Value stored in pointer:", *ptr)
*ptr = 20
fmt.Println("Updated value of x:", x)
}
Go 语言中类型转换说明
Go 语言支持类型转换,但需要注意一些规则和限制。例如:
package main
import"fmt"funcmain() {
// 显式类型转换var x int = 10var y float64 = float64(x)
fmt.Println(y)
// 类型别名的转换type Celsius float64type Fahrenheit float64
c := Celsius(25)
f := Fahrenheit(c*9/5 + 32)
fmt.Println(f)
}
4. 运算符
前提:chapter2 目录下创建 operator,学习总结如下:
算术运算符:+, -, *, /, %
逻辑运算符:&&, ||, !
比较运算符:==, !=, <, >, <=, >=
位运算符:&, |, ^, <<, >>, &^
新建 operator_test.go:
package operator
import (
"fmt""testing"
)
const (
Readable = 1 << iota
Writable
Executable
)
funcTestOperatorBasic(t *testing.T) {
a := 10
b := 5
fmt.Println("Sum:", a+b)
fmt.Println("Difference:", a-b)
fmt.Println("Product:", a*b)
fmt.Println("Quotient:", a/b)
fmt.Println("Remainder:", a%b)
x := true
y := false
fmt.Println("AND:", x && y)
fmt.Println("OR:", x || y)
fmt.Println("NOT:", !x)
fmt.Println("Equal:", a == b)
fmt.Println("Not Equal:", a != b)
fmt.Println("Greater Than:", a > b)
}
funcTestBitClear(t *testing.T) {
a := 7// 0111
a = a &^ Readable
a = a &^ Executable
t.Log(a&Readable == Readable, a&Writable == Writable, a&Executable == Executable)
}
按位清除运算符 &^
在 Go 语言中,&^ 是按位清除运算符(Bit Clear Operator)。它用于将某些位置上的位清零。
funcTestOther(t *testing.T) {
var a uint8 = 0b11001100 // 十进制为 204var b uint8 = 0b00110011 // 十进制为 51
result := a &^ b
fmt.Printf("a: %08b\n", a)
fmt.Printf("b: %08b\n", b)
fmt.Printf("Result: %08b\n", result) // 输出:11000000
fmt.Println("Result (Decimal):", result) // 输出:192
}
5. 条件语句(Conditional Statements)
前提:chapter2 目录下创建 condition,学习总结如下:
if 语句:基于条件来决定是否执行某段代码。
switch 语句:基于表达式的不同值执行不同的代码分支,无需 break。
创建 condition_test.go:
package condition
import (
"fmt""testing"
)
funcTestConditionIf(t *testing.T) {
age := 18if age < 18 {
fmt.Println("You are a minor.")
} elseif age >= 18 && age < 60 {
fmt.Println("You are an adult.")
} else {
fmt.Println("You are a senior citizen.")
}
}
funcTestConditionSwitch(t *testing.T) {
dayOfWeek := 3switch dayOfWeek {
case1:
fmt.Println("Monday")
case2:
fmt.Println("Tuesday")
case3:
fmt.Println("Wednesday")
default:
fmt.Println("Weekend")
}
}
6. 循环语句(Loop Statements)
前提:chapter2 目录下创建 loop,学习总结如下:
for 循环:支持初始化语句、循环条件和循环后的语句。
range 循环:用于迭代数组、切片、映射、字符串等可迭代的数据结构。
创建 loop_test.go:
package loop
import (
"fmt""testing"
)
funcTestLoopFor(t *testing.T) {
for i := 1; i <= 5; i++ {
fmt.Println("Iteration:", i)
}
}
funcTestLoopForRange(t *testing.T) {
numbers := []int{1, 2, 3, 4, 5}
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
}
funcTestLoopForUnLimit(t *testing.T) {
i := 1for {
fmt.Println("Iteration:", i)
i++
if i > 5 {
break
}
}
}
7. 跳转语句(Jump Statements)
前提:chapter2 目录下创建 jump,学习总结如下:
break:跳出循环。
continue:跳过本次循环迭代。
goto:跳转到指定标签处(不推荐使用)。
创建 jump_test.go:
package jump
import (
"fmt""testing"
)
funcTestJumpBreak(t *testing.T) {
for i := 1; i <= 5; i++ {
if i == 3 {
break
}
fmt.Println("Iteration:", i)
}
}
funcTestJumpContinue(t *testing.T) {
for i := 1; i <= 5; i++ {
if i == 3 {
continue
}
fmt.Println("Iteration:", i)
}
}
(三)常用集合和字符串
src 目录下创建 chapter3,在 Go 语言中,集合是存储一组值的数据结构。常用的集合类型包括数组、切片、映射和通道。
packagestringimport (
"strconv""strings""testing"
)
funcTestString(t *testing.T) {
var s string
t.Log(s)
s = "hello"
t.Log(len(s))
s = "中"
t.Log(len(s))
c := []rune(s)
t.Logf("中 unicode %x", c[0])
}
funcTestStringFn(t *testing.T) {
s := "A,B,C"
parts := strings.Split(s, ",")
for _, part := range parts {
t.Log(part)
}
t.Log(strings.Join(parts, "-"))
}
packagerecoverimport (
"fmt""testing"
)
funccleanup() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}
funcTestRecover(t *testing.T) {
defer cleanup()
panic("Something went wrong")
fmt.Println("This line will not be executed")
}
package series
import"fmt"funcinit() {
fmt.Println("init1")
}
funcSquare(n int)int {
return n * n
}
funcGetFibonacciSerie(n int) []int {
ret := []int{1, 1}
for i := 2; i < n; i++ {
ret = append(ret, ret[i-2]+ret[i-1])
}
return ret
}
3. 导入和应用远程依赖
使用 go get 命令来下载并添加远程依赖到项目中。
package remote
import (
"fmt""testing"
cm "github.com/easierway/concurrent_map"
)
funcTestConcurrentMap(t *testing.T) {
m := cm.CreateConcurrentMap(99)
m.Set(cm.StrKey("key"), 10)
value, ok := m.Get(cm.StrKey("key"))
if ok {
fmt.Println("Key found:", value)
}
}