Go by Example学习

news/2024/12/25 15:22:27/

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.ppmy.cn/news/1558028.html

相关文章

es 3期 第18节-分页查询使用避坑的一些事

#### 1.Elasticsearch是数据库&#xff0c;不是普通的Java应用程序&#xff0c;传统数据库需要的硬件资源同样需要&#xff0c;提升性能最有效的就是升级硬件。 #### 2.Elasticsearch是文档型数据库&#xff0c;不是关系型数据库&#xff0c;不具备严格的ACID事务特性&#xff…

ECharts散点图-气泡图,附视频讲解与代码下载

引言&#xff1a; ECharts散点图是一种常见的数据可视化图表类型&#xff0c;它通过在二维坐标系或其它坐标系中绘制散乱的点来展示数据之间的关系。本文将详细介绍如何使用ECharts库实现一个散点图&#xff0c;包括图表效果预览、视频讲解及代码下载&#xff0c;让你轻松掌握…

websocket的心跳检测和断线重连

心跳检测和断线重连可以通过WebSocket的事件和属性来实现。以下是一个简单的JavaScript示例&#xff0c;使用WebSocket API实现心跳检测和断线重连的功能&#xff1a; let ws;function connectWebSocket() {ws new WebSocket(ws://your-websocket-server-url);ws.onopen fun…

【uni-app】2025最新uni-app一键登录保姆级教程(包含前后端获取手机号方法)(超强避坑指南)

前言&#xff1a; 最近在配置uni-app一键登录时遇到了不少坑&#xff0c;uni-app的配套文档较为混乱&#xff0c;并且有部分更新的内容也没有及时更改在文档上&#xff0c;导致部分开发者跟着uni-app配套文档踩坑&#xff01;而目前市面上的文章质量也层次不齐&#xff0c;有的…

基于Spring Boot的动漫交流与推荐平台

一、开发背景与意义 动漫产业的蓬勃发展&#xff1a;随着动漫产业的不断壮大&#xff0c;动漫文化逐渐深入人心&#xff0c;吸引了大量爱好者。这一趋势推动了动漫作品的多样化和创新&#xff0c;同时也促进了相关产业的发展。 传统交流方式的局限性&#xff1a;传统的动漫交流…

ffmpeg.exe 命令使用

1. 视频分片&#xff1a;裁剪分割视频成小片段&#xff0c; ffmpeg Documentation Seeking – FFmpeg 1.指定持续时间 使用-t命令。前者要比后者快。 ffmpeg -ss [start] -i [input] -t [duration] -c copy [output] ffmpeg -i [input] -ss [start] -t [duration] -c cop…

告别卡顿:CasaOS轻NAS设备安装Gopeed打造高效下载环境

文章目录 前言1. 更新应用中心2.Gopeed安装与配置3. 本地下载测试4. 安装内网穿透工具5. 配置公网地址6. 配置固定公网地址 前言 无论你是需要大量文件传输的专业人士&#xff0c;还是只是想快速下载电影或音乐的普通用户&#xff0c;都会使用到下载工具。如果你对现有的下载工…

便签软件哪个好用 新款多功能便签软件哪个好?

在快节奏的现代生活中&#xff0c;便签软件已成为我们不可或缺的工具。无论是工作计划、生活琐事&#xff0c;还是灵感闪现&#xff0c;我们都需要一个可靠的助手来记录和提醒。面对市场上众多的便签软件&#xff0c;选择一个多功能且实用的便签软件显得尤为重要。 敬业签正是…