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()
}
相关推荐
canonical_entropy2 分钟前
Nop入门:增加DSL模型解析器
spring boot·后端·架构
代码or搬砖23 分钟前
Java集合-Set讲解
java·开发语言
艾上编程24 分钟前
第三章——爬虫工具场景之Python爬虫实战:学术文献摘要爬取,助力科研高效进行
开发语言·爬虫·python
渣娃-小晴晴24 分钟前
java集合在并发环境下应用时的注意事项
java·后端
明洞日记31 分钟前
【数据结构手册008】STL容器完全参考指南
开发语言·数据结构·c++
Jaising6661 小时前
PF4J 日志类冲突与 JVM 类加载机制
jvm·后端
jllllyuz1 小时前
matlab使用B样条进行曲线曲面拟合
开发语言·matlab
Undoom1 小时前
智能开发环境下的 Diagram-as-Code 实践:MCP Mermaid 技术链路拆解
后端
ku_code_ku2 小时前
python bert_score使用本地模型的方法
开发语言·python·bert
计算机毕设VX:Fegn08952 小时前
计算机毕业设计|基于springboot + vue图书借阅管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计