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()
}
相关推荐
这里有鱼汤4 分钟前
炒股的尽头真的是玄学?我用八字+AI做了个实验,结果震惊
后端
伐尘6 分钟前
【Qt】QTableWidget 自定义排序功能实现
开发语言·qt
hrrrrb9 分钟前
【Spring Security】认证(二)
java·后端·spring
程序员爱钓鱼15 分钟前
Python编程实战 · 基础入门篇 | Python的版本与安装
后端·python
舒克日记21 分钟前
基于springboot针对老年人的景区订票系统
java·spring boot·后端
GoldenaArcher31 分钟前
GraphQL 工程化篇 III:引入 Prisma 与数据库接入
数据库·后端·graphql
多多*35 分钟前
上传文件相关业务,采用策略模式+模版方法模式进行动态解耦
java·开发语言
沐雨橙风ιε42 分钟前
Spring Boot整合Apache Shiro权限认证框架(实战篇)
java·spring boot·后端·apache shiro
桦说编程1 小时前
CompletableFuture 异常处理常见陷阱——非预期的同步异常
后端·性能优化·函数式编程
李广坤1 小时前
Springboot解决跨域的五种方式
后端