当前位置:网站首页>Go语言高级
Go语言高级
2022-07-01 18:43:00 【游戏编程】
集合,通道,切片,错误处理,接口
package mainimport ( "fmt" "time")//8成员变量var i intvar s bool = falsefunc main() { //1 variable声明 //go中的String s要小写它没有类的概念 var s string = "林黛玉" var a int = 1 var b int = 1 fmt.Println(a + b) fmt.Println("hello world!") fmt.Println(s) var c, d int = 1, 2 fmt.Println(c + d) //2 变量声明 const e, f = "薛宝钗", "贾宝玉" fmt.Println(e + f) //3 判断语句 if s == "林黛玉" { fmt.Println("111") } else { fmt.Println("222") } //4 循环语句 for i := 0; i < 5; i++ { fmt.Println(i) } /*for true { fmt.Println("林姐姐") }*/ // 7函数调用 var res int = max(a, d) fmt.Println(res) // 9数组 var arr = [4]int{1, 24, 45, 6} fmt.Println(arr) i2 := arr[0] fmt.Println(i2) for i := 0; i < len(arr); i++ { fmt.Println(arr[i]) } for i3 := range arr { fmt.Println(i3) } //10内存地址 var m int = 23 //&是go中的去地址符号 内存地址 fmt.Println("m在内存中的地址值是:", &m) //m在内存中的地址值是: 0xc000018140 //11指针:一个指针变量指向了一个值的内存地址。 //12声明 //var r *float32 //定义指针变量。 var m1 int = 12 //为指针变量赋值。 var p *int //指针 fmt.Println("m1在内存中的地址值是", m1) fmt.Println("p在内存中的地址值是:", &p) //访问指针变量中指向地址的值。 p = &m1 //指针指向了12 //通过指针访问值 fmt.Println("p的值:", *p) //空指针 var point *int //按照for循环去理解 fmt.Println("空指针:", point) //空指针: <nil> //14 实例化一个结构体 fmt.Println("新的结构体:", Books{"曹雪芹", "红楼梦", "文献学", 1}) //实例化一个结构体类型(创建对象) var Book1 Books var Book2 Books //get set方法为属性赋值 Book1.title = "西游记" Book1.anthor = "吴承恩" Book2.book_id = 1333 Book2.subject = "战争类" fmt.Println(Book1) fmt.Println(Book2) //结构体作为函数参数 print(Book2) //15切片,对数组扩容(相当于动态数组) var slice []int = make([]int, 3) slice = make([]int, 3) //简写 slice = []int{1, 3, 5} //init fmt.Println(slice) //[1 3 5] var nums = make([]int, 3, 5) //t,len,cap printMethod(nums) //3 5 [0 0 0]空切片nil //切片截取 /*var array = [5]int{1, 2, 1, 3, 8} var slice01 = make(arr, 4, 6)*/ //创建切片 slice01 := []int{1, 2, 1, 3, 8} printMethod(slice01) fmt.Println("原始切片", slice01) //原始切片 [1 2 1 3 8] fmt.Println("打印从索引1-4的所有元素,包含1,但不包含4", slice01[1:4]) //append()() var nums01 []int //定义一个切片 printMethod(nums01) //0 0 [] nums01 = append(nums01, 1) nums01 = append(nums01, 6) fmt.Println(nums01) //[1 6] //copy() slice02 := make([]int, len(nums01), cap((nums01))*2) fmt.Println(slice02) copy(slice02, nums01) //nums01拷贝到slice02 printMethod(slice02) //2 4 [1 6] //16增强for循环 var array01 = []int{1, 2, 1, 3, 8} for i3 := range array01 { fmt.Println(i3) } map1 := make(map[int]float32) map1[0] = 1.0 map1[1] = 2.0 map1[2] = 3.0 map1[3] = 4.0 map1[4] = 1.0 for key, val := range map1 { fmt.Println(key, val) } for key := range map1 { fmt.Println(key) } for _, val := range map1 { fmt.Println(val) }}func printMethod(num []int) { fmt.Println(len(num), cap(num), num)}func print(books Books) { fmt.Println(books.book_id) fmt.Println(books.subject) fmt.Println(books.title) fmt.Println(books.anthor) //17map集合 var map2 map[string]string map2 = make(map[string]string) map2["荣国府"] = "贾宝玉" map2["宁国府"] = "贾惜春" fmt.Println(map2) //map[宁国府:贾惜春 荣国府:贾宝玉] delete(map2, "宁国府") fmt.Println(map2) //map[荣国府:贾宝玉] //18递归函数 //method() //fatal error: stack overflow //Go 语言支持递归。但我们在使用递归时,开发者需要设置退出条件,否则递归将陷入无限循环中。 //递归函数对于解决数学上的问题是非常有用的,就像计算阶乘,生成斐波那契数列等。 fmt.Println("12的阶乘是:", Factorial(12)) //479001600 for i := 0; i < 10; i++ { fmt.Println(fibonacci(i)) //0 1 1 2 3 //5 //8 //13 //21 //34 } //19类型转换 var a1 int = 17 var b1 int = 5 var res float32 res = float32(a1) / float32(b1) fmt.Println(res) //3.4 //不支持隐式转化,即大转小 //20go语言接口 var red Red red = new(NingRed) red.sleep() red = new(RongRed) red.sleep() //错误处理 //分母不为0 if result, errorMsg := Divide(4, 2); errorMsg == "" { fmt.Println(result) } //分母为0 if _, errorMsg := Divide(2, 0); errorMsg != "" { fmt.Println(errorMsg) } //21go并发 go say("贾宝玉") //go必须在say之前call,否则一直是say say("林") //执行以上代码,你会看到输出的 hello 和 world // 是没有固定先后顺序。因为它们是两个 goroutine 在执行: //通道 //创建channel chdemo := make(chan int) fmt.Println(chdemo) //0xc00018a000 s := []int{1, 2, 4, 5, 6} ch := make(chan int) go sum(s[:len(s)/2], ch) go sum(s[len(s)/2:], ch) m, n := <-ch, <-ch fmt.Println(m, n, m+n) sum(s, ch) //all goroutines are asleep - deadlock! //缓冲区 /* 带缓冲区的通道允许发送端的数据发送和接收端的数据获取处于异步状态, 就是说发送端发送的数据可以放在缓冲区里面,可以等待接收端去获取数据,而不是立刻需要接收端去获取数据。*/ ch02 := make(chan int, 2) ch03 := make(chan int, 3) ch02 <- 4 ch03 <- 6 fmt.Println(<-ch02) fmt.Println(<-ch03) //遍历通道 c := make(chan int, 10) go itator(cap(c), c) for i := range c{ fmt.Println(i) }}func itator(a int, ch chan int) { x, y := 1, 2 for i := 0; i < a; i++ { ch <- x x, y = y, x+y } close(ch)}func sum(arr []int, ch01 chan int) { sum := 0 for i5 := range arr { sum += i5 ch01 <- sum //把sum赋给ch01 }}func say(s string) { for i := 0; i < 5; i++ { time.Sleep(time.Millisecond * 100) fmt.Println("---", s) }}//定义一个错误结构体type errorDemo struct { demo1 int demo2 int}func (de *errorDemo) Error() string { strFormat := ` 0不能作为分母 demo1 = %d demo2 = 0` return fmt.Sprintf(strFormat, de.demo1)}func Divide(a3 int, b3 int) (result int, errorMsg string) { if b3 == 0 { data := errorDemo{ demo1: a3, demo2: b3, } errorMsg = data.Error() return } else { return a3 / b3, "" }}type Red interface { sleep()}type NingRed struct {}func (ningRed NingRed) sleep() { fmt.Println("红楼梦里有宁国府,史湘云醉卧芍药因")}type RongRed struct {}func (rongRed RongRed) sleep() { fmt.Println("红楼梦里有荣国府,滴翠亭杨妃戏彩蝶")}func fibonacci(n int) int { if n < 2 { return n } return fibonacci(n-2) + fibonacci(n-1)}func Factorial(n uint64) (result uint64) { if n > 0 { result = n * Factorial(n-1) return result } return 1}func method() { method()}//13结构体(相当于java中的对象)type Books struct { //结构体定义需要使用 type 和 struct 语句。struct //语句定义一个新的数据类型,结构体中有一个或多个成员。type 语句设定了结构体的名称。结构体的格式如下: //定义结构体不能用var anthor string title string subject string book_id int}// 6函数声明func max(num1, num2 int) int { /* 声明局部变量 */ var result int if num1 > num2 { result = num1 } else { result = num2 } return result}
作者:天禄燃藜
游戏编程,一个游戏开发收藏夹~
如果图片长时间未显示,请使用Chrome内核浏览器。
边栏推荐
- 如何使用物联网低代码平台进行个人设置?
- 数据库基础:select基本查询语句
- 【6.24-7.1】写作社区精彩技术博文回顾
- 毕业季 | 华为专家亲授面试秘诀:如何拿到大厂高薪offer?
- 1. "Create your own NFT collections and publish a Web3 application to show them." what is NFT
- AppGallery Connect场景化开发实战—图片存储分享
- 一次SQL优化,数据库查询速度提升 60 倍
- The former 4A executives engaged in agent operation and won an IPO
- 华为游戏初始化init失败,返回错误码907135000
- Leetcode-141 circular linked list
猜你喜欢
Clean up system cache and free memory under Linux
宝,运维100+服务器很头疼怎么办?用行云管家!
Huawei cloud experts explain the new features of gaussdb (for MySQL)
制造业SRM管理系统供应商全方位闭环管理,实现采购寻源与流程高效协同
MySQL common graphics management tools | dark horse programmers
Once the SQL is optimized, the database query speed is increased by 60 times
一次SQL优化,数据库查询速度提升 60 倍
AI training speed breaks Moore's law; Song shuran's team won the RSS 2022 Best Paper Award
Dlib+Opencv库实现疲劳检测
2. Create your own NFT collections and publish a Web3 application to show them start and run your local environment
随机推荐
Golang error handling
Netease games, radical going to sea
[quick application] there are many words in the text component. How to solve the problem that the div style next to it will be stretched
VBA simple macro programming of Excel
[6.24-7.1] review of wonderful technical blog posts in the writing community
B2B e-commerce platform solution for fresh food industry to improve the standardization and transparency of enterprise transaction process
组队学习! 14天鸿蒙设备开发“学练考”实战营限时免费加入!
Usage and underlying implementation principle of PriorityQueue
水产行业智能供应链管理平台解决方案:支撑企业供应链数字化,提升企业管理效益
lefse分析
Viewing technological changes through Huawei Corps (VI): smart highway
Leetcode-21 combines two ordered linked lists
The best landing practice of cave state in an Internet ⽹⾦ financial technology enterprise
数商云:从规划到落地,五矿集团如何快速构建数字化发展新格局?
Lake Shore continuous flow cryostat transmission line
ES6数组方法find()、findIndex()的总结「建议收藏」
Lumiprobe phosphide hexaethylene phosphide specification
js找出数字在数组中下一个相邻的元素
Cdga | if you are engaged in the communication industry, you should get a data management certificate
Specification of lumiprobe reactive dye indocyanine green