当前位置: 首页 > news >正文

Go by Example学习

2024.12.21

  • 000
  • array slice
  • map
  • range
  • 函数
  • 结构体
  • 接口

参考资料:
https://gobyexample-cn.github.io/

000

package mainimport ("fmt""math"
)const s string = "constant"func main() {fmt.Println("hello world")var a = "initial"fmt.Println(a)var b, c int = 1, 2fmt.Println(b, c)var d = truefmt.Println(d)var e int fmt.Println(e)f := "short"fmt.Println(f)fmt.Println(s)const n = 50000000const dd = 3e20 / nfmt.Println(dd)fmt.Println(int64(dd))fmt.Println(math.Sin(n))i := 1for i <= 3 {fmt.Print(i)i = i + 1}for j := 7; j <= 9; j ++ {fmt.Println(j)}for {fmt.Println("loop")break}for n := 0; n <= 5; n ++ {if n % 2 == 0 {continue}fmt.Println(n)}if 7 % 2 == 0 {fmt.Println("7 is even")} else {fmt.Println("7 is odd")}if 8 % 4 == 0 {fmt.Println("8 is divisible by 4")}if num := 9; num < 0 {fmt.Println(num, "is negative")} else if num < 10 {fmt.Println(num, "has 1 digit")} else {fmt.Println(num, "has multiple digits")}}

array slice

package mainimport ("fmt""time"
)func main() {i := 2fmt.Print("write ", i, " as ")switch i {case 1: fmt.Println("one")case 2:fmt.Println("two")case 3:fmt.Println("three")}switch time.Now().Weekday() {case time.Saturday, time.Sunday:fmt.Println("It's the weekend")default:fmt.Println("It's a weekday")}fmt.Println(time.Now().Weekday())t := time.Now()switch {case t.Hour() < 12:fmt.Println("It's before noon")default:fmt.Println("It's after noon")}whatAmI := func(i interface{}) {switch t := i.(type) {case bool:fmt.Println("I'm a bool")case int:fmt.Println("I'm an int")default:fmt.Printf("Don't know type %T\n", t)}}whatAmI(true)whatAmI(1)whatAmI("hey")var a [5]intfmt.Println("emp: ", a)a[4] = 100fmt.Println("set:", a)fmt.Println("get:", a[4])fmt.Println("len:", len(a))b := [5]int{1, 2, 3, 4, 5}fmt.Println("dcl: ", b)// b = append(b, 777)// fmt.Println("dcl: ", b)var twoD [2][3]intfor i := 0; i < 2; i ++ {for j := 0; j < 3; j ++ {twoD[i][j] = i + j}}fmt.Println("2d: ", twoD)// slicett := []string{"g", "h", "i"}fmt.Println("len: ", len(tt))fmt.Println("dcl:", tt)tt = append(tt, "hh")fmt.Println("dcl:", tt)s := make([]string, 4)fmt.Println("len: ", len(s))fmt.Println("emp:", s)s[0] = "a"s[1] = "b"s[2] = "c"fmt.Println("set:", s)fmt.Println("len: ", len(s))mat := make([][]int, 3)for i := 0; i < 3; i ++ {innerLen := i + 1mat[i] = make([]int, innerLen)for j := 0; j < innerLen; j ++ {mat[i][j] = i + j}}fmt.Println("2d: ", mat)
}

map

package mainimport "fmt"func main() {m := make(map[string]int)fmt.Println(m)m["k1"] = 7m["k2"] = 13fmt.Println("map: ", m)v1 := m["k1"]fmt.Println("v1: ", v1)fmt.Println("len: ", len(m))delete(m, "k2")fmt.Println("map: ", m)_, prs := m["k2"]fmt.Println("prs:", prs)n := map[string]int{"foo": 1, "bar": 2}fmt.Println("map: ", n)}

range

package mainimport "fmt"func main() {nums := []int{2, 3, 4}sum := 0for _, num := range nums {sum += num}fmt.Println("sum: ", sum)for i, num := range nums {if num == 3 {fmt.Println("index: ", i)}}hash := map[string]string{"a": "apple", "b": "banana"}for k, v := range hash {fmt.Printf("%s -> %s\n", k, v)}for k := range hash {fmt.Println("key: ", k)}for i, c := range "go" {fmt.Println(i, c)fmt.Printf("%d %c\n", i, c)}
}

函数

package mainimport "fmt"func plus (a int, b int) int {return a + b
}func plusPlus (a, b, c int) int {return a + b + c
}func vals() (int, int) {return 3, 7
}// 变参函数
func sum(nums ...int) {fmt.Print(nums, " ")total := 0for _, num := range nums {total += num}fmt.Println(total)
}// 闭包
func intSeq() func() int {i := 0return func() int {i ++return i}
}func main() {res := plus(1, 2)fmt.Println(res)res = plusPlus(1, 2, 3)fmt.Println(res)a, b := vals()fmt.Println(a)fmt.Println(b)_, c := vals()fmt.Println(c)sum(1, 2)sum(1, 2, 3)nums := []int{1, 2, 3, 4}sum(nums...)nextInt := intSeq()fmt.Println(nextInt())fmt.Println(nextInt())fmt.Println(nextInt())newInts := intSeq()fmt.Println(newInts())// 闭包递归, var显式声明var fib func(n int) intfib = func(n int) int {if n < 2 {return n}return fib(n - 1) + fib(n - 2)}fmt.Println(fib(7))}
// 指针
package main import "fmt"func zeroval(x int) {x = 0
}
func zeroptr(x *int) {*x = 0
}func main() {i := 1fmt.Println("initial: ", i)zeroval(i)fmt.Println("zeroval: ", i)zeroptr(&i)fmt.Println("zeroptr: ", i)fmt.Println("pointer: ", &i)}

结构体

package mainimport "fmt"type person struct {name stringage int
}
func newPerson(name string) *person {p := person{name: name}p.age = 42return &p
}type rect struct {width, height int
}
// 结构体的方法
func (r *rect) area() int {return r.width * r.height
}
func (r rect) perim() int {return 2 * r.width + 2 * r.height
}func main() {fmt.Println(person{"Bob", 20})fmt.Println(person{name: "Alice", age: 30})fmt.Println(person{name: "Fred"})fmt.Println(&person{name: "Ann", age: 40})fmt.Println(newPerson("Jon"))s := person{name: "Sean", age: 50}fmt.Println(s.name)sp := &s // 指针也可以.访问,自动解引用fmt.Println(sp.age)sp.age = 51 // 可变fmt.Println(*sp)// 结构体的方法r := rect{width: 10, height: 5}fmt.Println("area: ", r.area())fmt.Println("perim: ", r.perim())rp := &rfmt.Println("area: ", rp.area())fmt.Println("perim: ", rp.perim())}

接口

package mainimport ("fmt""math"
)type geometry interface {area() float64perim() float64
}type rect struct {width, height float64
}
type circle struct {radius float64
}
// 实现接口方法即可
func (r rect) area() float64 {return r.width * r.height
}func (r rect) perim() float64 {return 2 * r.width + 2 * r.height
}
// 实现接口方法即可
func (c circle) area() float64 {return math.Pi * c.radius * c.radius
}func (c circle) perim() float64 {return 2 * math.Pi * c.radius
}func measure(g geometry) { // 实现类fmt.Println(g)fmt.Println(g.area())fmt.Println(g.perim())
}func main() {r := rect{width: 3, height: 4}c := circle{radius: 5}measure(r)measure(c)
}

http://www.mrgr.cn/news/81018.html

相关文章:

  • SpringBoot Redis 消息队列
  • Java模拟Mqtt客户端连接Mqtt Broker
  • idea无法识别文件,如何把floder文件恢复成model
  • 端到端自动驾驶大模型:视觉-语言-动作模型 VLA
  • IDEA无法打开插件市场的解决
  • Kubernetes(k8s)安装详细过程
  • LeetCode 刷题笔记
  • qemu源码解析【06】qemu启动初始化流程
  • Ubuntu 22.04,Rime / luna_pinyin.schema 输入法:外挂词库,自定义词库 (****) OK
  • Docker 入门:如何使用 Docker 容器化 AI 项目(一)
  • ubuntu 安装更新 ollama新版本
  • CAD xy坐标标注(跟随鼠标位置实时移动)——C#插件实现
  • 备忘一个FDBatchMove数据转存的问题
  • 分析excel硕士序列数据提示词——包含对特征的筛选,非0值的过滤
  • Halcon单相机+机器人=眼在手上#标定心得
  • SQL进阶技巧:如何计算商品需求与到货队列表进出计划?
  • Linux Shell 脚本编程基础知识篇(一)
  • Restaurants WebAPI(三)——Serilog/FluenValidation
  • Jenkins
  • lc148链表排序——链表版归并排序
  • AI的进阶之路:从机器学习到深度学习的演变(二)
  • 【老白学 Java】泛型应用 - 卡拉 OK(四)
  • git merge 冲突 解决 show case
  • FFmpeg 4.3 音视频-多路H265监控录放C++开发二十一.2,RTP协议-RTP协议概述,协议详情
  • JS数组方法汇总
  • 【算法】编程拓展-C语言-期末复习