Golang基础学习 Go 语言教程 | 菜鸟教程 (it028.com)
goland开发环境搭建及运行第一个go程序HelloWorld_goland helloworld-CSDN博客
基础语法 Go 语言教程 | 菜鸟教程 (it028.com)
语句后不需要;
{
不能单独一列
switch 注意switch支持多值匹配:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package mainimport ( "fmt" ) func main () { day := "Thursday" switch day { case "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" : fmt.Println(day, "is a weekday." ) case "Saturday" , "Sunday" : fmt.Println(day, "is a weekend." ) default : fmt.Println(day, "is not a valid day." ) } }
fallthrough关键字强制执行下一个case的内容,switch不需要break(但java需要)
注意if和switch没有()的使用
函数定义: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 package mainimport "fmt" func add (a int , b int ) int { var result int result = a + b return result } func main () { a := 2 b := 3 ans := add(a, b) fmt.Printf("ans is %d" , ans) } func addAndMutiply (a,b int ) (int ,int ){ var result1 int var result2 int result1 = a+b result2 = a*b return result1,result }
数组: 1 2 3 var nums[5 ] int var nums = [5 ]int {0 ,1 ,2 ,3 ,4 }var nums = []int {1 ,3 ,5 ,7 ,9 ,10 }
获取数组长度:
指针: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 var a int var ptr *int ptr = &a fmt.Printf("the num is %d\n" ,a) fmt.Printf("the address of a is %x\n" ,&a) fmt.Printf("the address is %x\n" ,ptr) fmt.Printf("the num of the address is %d\n" ,*ptr) var nullPtr *int fmt.Printf("nullPtr的值为%x" ,nullPtr) if (nullPtr==nil )
结构体和结构体指针: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 package mainimport "fmt" type Books struct { title string author string subject string book_id int } func main () { var Book1 Books var Book2 Books Book1.title = "Go 语言" Book1.author = "www.runoob.com" Book1.subject = "Go 语言教程" Book1.book_id = 6495407 Book2.title = "Python 教程" Book2.author = "www.runoob.com" Book2.subject = "Python 语言教程" Book2.book_id = 6495700 fmt.Printf( "Book 1 title : %s\n" , Book1.title) fmt.Printf( "Book 1 author : %s\n" , Book1.author) fmt.Printf( "Book 1 subject : %s\n" , Book1.subject) fmt.Printf( "Book 1 book_id : %d\n" , Book1.book_id) fmt.Printf( "Book 2 title : %s\n" , Book2.title) fmt.Printf( "Book 2 author : %s\n" , Book2.author) fmt.Printf( "Book 2 subject : %s\n" , Book2.subject) fmt.Printf( "Book 2 book_id : %d\n" , Book2.book_id) } package mainimport "fmt" type Books struct { title string author string subject string book_id int } func main () { var Book1 Books var Book2 Books Book1.title = "Go 语言" Book1.author = "www.runoob.com" Book1.subject = "Go 语言教程" Book1.book_id = 6495407 Book2.title = "Python 教程" Book2.author = "www.runoob.com" Book2.subject = "Python 语言教程" Book2.book_id = 6495700 printBook(&Book1) printBook(&Book2) } func printBook ( book *Books ) { fmt.Printf( "Book title : %s\n" , book.title) fmt.Printf( "Book author : %s\n" , book.author) fmt.Printf( "Book subject : %s\n" , book.subject) fmt.Printf( "Book book_id : %d\n" , book.book_id) }
切片: 1 2 3 4 5 6 7 8 9 10 len :=3 cap :=5 var nums[] int = make ([]int ,len )var nums2[] int = make ([]int ,len ,cap ) var arr[] int = []int {5 ,6 ,7 ,1 ,2 }var s[] int = arr[:] s2[] = arr[0 :5 ]
完整的切片例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 package mainimport "fmt" func main () { numbers := []int {0 ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 } printSlice(numbers) fmt.Println("numbers ==" , numbers) fmt.Println("numbers[1:4] ==" , numbers[1 :4 ]) fmt.Println("numbers[:3] ==" , numbers[:3 ]) fmt.Println("numbers[4:] ==" , numbers[4 :]) numbers1 := make ([]int ,0 ,5 ) printSlice(numbers1) number2 := numbers[:2 ] printSlice(number2) number3 := numbers[2 :5 ] printSlice(number3) } func printSlice (x []int ) { fmt.Printf("len=%d cap=%d slice=%v\n" ,len (x),cap (x),x) }
切片的append和copy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 package mainimport "fmt" func main () { var numbers []int printSlice(numbers) numbers = append (numbers, 0 ) printSlice(numbers) numbers = append (numbers, 1 ) printSlice(numbers) numbers = append (numbers, 2 ,3 ,4 ) printSlice(numbers) numbers1 := make ([]int , len (numbers), (cap (numbers))*2 ) copy (numbers1,numbers) printSlice(numbers1) } func printSlice (x []int ) { fmt.Printf("len=%d cap=%d slice=%v\n" ,len (x),cap (x),x) }
range: Go 语言中 range 关键字用于 for 循环中迭代数组(array)、切片(slice)、通道(channel)或集合(map)的元素。在数组和切片中它返回元素的索引和索引对应的值,在集合中返回 key-value 对。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 package mainimport "fmt" func main () { nums := []int {2 , 3 , 4 } sum := 0 for _, num := range nums { sum += num } fmt.Println("sum:" , sum) for i, num := range nums { if num == 3 { fmt.Println("index:" , i) } } kvs := map [string ]string {"a" : "apple" , "b" : "banana" } for k, v := range kvs { fmt.Printf("%s -> %s\n" , k, v) } for i, c := range "go" { fmt.Println(i, c) } }
结果:
1 2 3 4 5 6 sum: 9 index: 1 a -> apple b -> banana 0 103 1 111
Map: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 package mainimport "fmt" func main () { var countryCapitalMap map [string ]string countryCapitalMap = make (map [string ]string ) countryCapitalMap [ "France" ] = "巴黎" countryCapitalMap [ "Italy" ] = "罗马" countryCapitalMap [ "Japan" ] = "东京" countryCapitalMap [ "India " ] = "新德里" for country := range countryCapitalMap { fmt.Println(country, "首都是" , countryCapitalMap [country]) } capital, ok := countryCapitalMap [ "American" ] if (ok) { fmt.Println("American 的首都是" , capital) } else { fmt.Println("American 的首都不存在" ) } }
delete函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 package mainimport "fmt" func main () { countryCapitalMap := map [string ]string {"France" : "Paris" , "Italy" : "Rome" , "Japan" : "Tokyo" , "India" : "New delhi" } fmt.Println("原始地图" ) for country := range countryCapitalMap { fmt.Println(country, "首都是" , countryCapitalMap [ country ]) } delete (countryCapitalMap, "France" ) fmt.Println("法国条目被删除" ) fmt.Println("删除元素后地图" ) for country := range countryCapitalMap { fmt.Println(country, "首都是" , countryCapitalMap [ country ]) } }
1 2 3 4 5 6 7 8 9 10 原始地图 India 首都是 New delhi France 首都是 Paris Italy 首都是 Rome Japan 首都是 Tokyo 法国条目被删除 删除元素后地图 Italy 首都是 Rome Japan 首都是 Tokyo India 首都是 New delhi
接口 Go 语言提供了另外一种数据类型即接口,它把所有的具有共性的方法定义在一起,任何其他类型只要实现了这些方法就是实现了这个接口。
接口->结构->func(结构)call(){}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 package mainimport ( "fmt" ) type Phone interface { call() } type NokiaPhone struct {} func (nokiaPhone NokiaPhone) call() { fmt.Println("I am Nokia, I can call you!" ) } type IPhone struct {} func (iPhone IPhone) call() { fmt.Println("I am iPhone, I can call you!" ) } func main () { var phone Phone phone = new (NokiaPhone) phone.call() phone = new (IPhone) phone.call() }
1 2 I am Nokia, I can call you! I am iPhone, I can call you!
错误处理
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 package mainimport ( "fmt" ) type DivideError struct { dividee int divider int } func (de *DivideError) Error() string { strFormat := ` Cannot proceed, the divider is zero. dividee: %d divider: 0 ` return fmt.Sprintf(strFormat, de.dividee) } func Divide (varDividee int , varDivider int ) (result int , errorMsg string ) { if varDivider == 0 { dData := DivideError{ dividee: varDividee, divider: varDivider, } errorMsg = dData.Error() return } else { return varDividee / varDivider, "" } } func main () { if result, errorMsg := Divide(100 , 10 ); errorMsg == "" { fmt.Println("100/10 = " , result) } if _, errorMsg := Divide(100 , 0 ); errorMsg != "" { fmt.Println("errorMsg is: " , errorMsg) } }
并发/协程 Go 并发 | 菜鸟教程 (it028.com)
golang学习笔记(协程的基础知识)_协程 golang-CSDN博客
在Go语言中,要创建一个协程,只需在函数调用前加上关键字”go”。下面是一个简单的示例:
这样就创建了一个新的协程,并在该协程中执行相应的函数。协程会与主线程并发执行,不会阻塞主线程的执行。
协程之间可以通过通道(Channel)进行通信。通道是一种在多个协程之间同步和传递数据的机制,它能够保证并发安全。通过通道,协程可以发送和接收数据,实现协程之间的协作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 package mainimport ( "fmt" "time" ) func longRunningTask () (res int ) { time.Sleep(time.Second) for i := 0 ; i < 10 ; i++ { res += i } return res } func main () { result := make (chan int ) go func () { result <- longRunningTask() }() fmt.Println("Waiting for result..." ) fmt.Println("Result:" , <-result) }
make和new [深入理解 Golang 中 New() 和 make() 的区别_golang new-CSDN博客](https://blog.csdn.net/qq_53742640/article/details/137696417?ops_request_misc=&request_id=&biz_id=102&utm_term=golang make&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-1-137696417.nonecase&spm=1018.2226.3001.4187)
[golang 中 new 和 make 详解_golang make new-CSDN博客](https://blog.csdn.net/u012730525/article/details/136390719?ops_request_misc=&request_id=&biz_id=102&utm_term=golang make&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-2-136390719.nonecase&spm=1018.2226.3001.4187)
包管理 Golang 基础 Go Modules包管理_golang包管理-CSDN博客
go怎么引入其他Go package文件(vscode中)_go怎么引入别的文件-CSDN博客
注意GOPATH和go.mod不能共存,用go.mod好一些
$GOPATH/go.mod exists but should not-CSDN博客