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()
}
相关推荐
2501_931803751 分钟前
Go:一门为解决C语言痛点而生的现代语言
c语言·开发语言·golang
zhengzizhe4 分钟前
ReBAC 与 Google Zanzibar:权限系统的未来
后端·架构
用户8356290780519 分钟前
使用 Python 自动创建 Excel 折线图
后端·python
梅兮昂18 分钟前
Cloudflare Tunnel 实践教程
后端
倒流时光三十年23 分钟前
PostgreSQL VACUUM 清理机制详解
后端
geovindu30 分钟前
go: Interpreter Pattern
开发语言·设计模式·golang·解释器模式
小白学大数据43 分钟前
面向大规模爬取:Python 全站链接爬虫优化(过滤 + 断点续爬)
开发语言·爬虫·python
良木生香1 小时前
【C++初阶】STL——List从入门到应用完全指南(1)
开发语言·数据结构·c++·程序人生·算法·蓝桥杯·学习方法
Alice-YUE1 小时前
【无标题】
开发语言·javascript·ecmascript
折哥的程序人生 · 物流技术专研1 小时前
《Java面试85题图解版(二)》进阶深化中篇:Spring核心 + 数据库进阶
java·后端·spring·面试