Go入门示例

这里写自定义目录标题

视频

点击看视频

值传递、引用传递、指针

直接给个例子吧:

go 复制代码
package main

import "fmt"

// 值传递
func changeInteger(number int) {
	number += 1
}

// 引用传递
func changeSize(s []string) {

	for index, value := range s {
		s[index] = fmt.Sprintf("%d:%s", index, value)
	}

}

// Coordinate 指针类型
type Coordinate struct {
	x, y int
}

func changeStruct(c Coordinate) {
	c.x = 3
	c.y = 3
}

func changeStruct2(c *Coordinate, step int) {
	c.x = c.x + step
}

func main() {

	fmt.Println("Example Start")
	num := 1
	changeInteger(num)
	fmt.Println(num)

	lang := []string{"English", "Math", "Chinese"}
	fmt.Println(lang)
	changeSize(lang)
	fmt.Println(lang)

	point1 := Coordinate{1, 1}
	fmt.Println(point1)
	changeStruct(point1)
	fmt.Println(point1)

	changeStruct2(&point1, 4)
	fmt.Println(point1)
	changeStruct2(&point1, 5)
	fmt.Println(point1)

}

多线程

go 复制代码
//ex1 goroutine wg
func learnLang(s string, wg *sync.WaitGroup) {
	defer wg.Done()
	fmt.Println("try to code learn ", s)
}

var wg sync.WaitGroup

func exampleOne() {
	var langWord = []string{
		"C",
		"C++",
		"Java",
		"Python",
		"C#",
	}
	wg.Add(len(langWord))
	for index, word := range langWord {
		go learnLang(fmt.Sprintf("learn %d. %s", index, word), &wg)
	}
	wg.Wait()

	fmt.Println("end")
}
go 复制代码
// ex2 channel
func createChannel1(ch chan string) {

	for {
		time.Sleep(4 * time.Second)
		ch <- "this is from channel 1"
	}

}

func createChannel2(ch chan string) {

	for {
		time.Sleep(2 * time.Second)
		ch <- "this is from channel 2"
	}

}

func exampleTwo() {

	fmt.Println("this is the example 2")

	ch1 := make(chan string)
	ch2 := make(chan string)

	go createChannel1(ch1)
	go createChannel2(ch2)

	for {
		select {
		case string1 := <-ch1:
			fmt.Println("string 1 get: ", string1)
		case string2 := <-ch2:
			fmt.Println("string 2 get: ", string2)
		default:
			time.Sleep(1 * time.Second)
			fmt.Println("I can't stop")
		}
	}

}
go 复制代码
func main() {
	exampleOne()
	//exampleTwo()
}
相关推荐
写码跑山的老艾25 分钟前
优惠券为何能反复使用?一次算价与提单不一致的资损复盘
后端
RAG学徒loading1 小时前
我把 RAG 召回从 57.6% 做到 78.8%,然后发现 75% 的真实问题它答不了
后端
用户42569399996201 小时前
我的 HashMap 查找全废了,但 36 个测试全绿
后端
小番茄程序猿1 小时前
Redis 编码压测 59 轮:HSET 快 23 倍是假象,SMEMBERS 慢 30 倍是真的
redis·后端
BaiPeter1 小时前
ZPL文件预览
开发语言·c++
Moment1 小时前
代码都能让 Agent 写了,我们为什么还要学前端?
前端·后端·面试
AI入职记2 小时前
Spring AI 实测:不挂工具,模型真的会瞎编吗?
后端·ai编程
wei_shuo2 小时前
SQL Server数据迁移实战:内置故障诊断工具与根因分析实践
后端
一条Go2 小时前
告警指纹:一次故障为什么只产生一条 FIRING 记录
后端·架构·github