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)

}

多线程

//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")
}
// 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")
		}
	}

}
func main() {
	exampleOne()
	//exampleTwo()
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值