Golang Basic - select and channel usage

前端之家收集整理的这篇文章主要介绍了Golang Basic - select and channel usage前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

今天学习了一下Golang 的 tag,select 和 channel ,记录在此!

1.tag 的作用

package main

import (
	"encoding/json"
	"fmt"
	"reflect"
)

type Accout struct {
	UserId   int    `json:"user_id" bson:"user_id"`
	UserName string `json:"user_name" bson:"user_name"`
	Password string `json:"pass_word" bson:"pass_word"`
}

func main() {
	account := &Accout{UserId: 1,UserName: "justin",Password: "12345"}
	accountJson,_ := json.Marshal(account)
	fmt.Println(string(accountJson))

	t := reflect.TypeOf(account)

	for i := 0; i < 3; i++ {
		field := t.Elem().Field(i)
		fmt.Println(field.Tag.Get("json"))
		fmt.Println(field.Tag.Get("bson"))
	}
}
输出

{"user_id":1,"user_name":"justin","pass_word":"12345"}
user_id
user_id
user_name
user_name
pass_word
pass_word
2.select 和 channel

package main

import (
	"fmt"
	"strconv"
	"time"
)

func test1() {
	ch1 := make(chan int,1)
	ch2 := make(chan int,1)

	ch1 <- 1
	ch2 <- 1

	select {
	case <-ch1:
		fmt.Println("ch1 pop one element")
	case <-ch2:
		fmt.Println("ch2 pop one element")
	}
}

func test2() {
	timeout := make(chan bool,1)
	ch := make(chan int,1)
	ch <- 1
	go func() {
		time.Sleep(3000)
		timeout <- true
	}()

	select {
	case <-ch:
		fmt.Println("got value")
	case <-timeout:
		fmt.Println("timeout")
	}
}

func test3() {
	taskChan := make(chan string,3)
	doneChan := make(chan bool,1)

	for i := 0; i < 3; i++ {
		taskChan <- strconv.Itoa(i)
		fmt.Println("send: ",i)
	}

	go func() {
		for i := 0; i < 3; i++ {
			task := <-taskChan
			fmt.Println("received: ",task)
		}
		doneChan <- true
	}()

	<-doneChan
}

func main() {
	test2()
}
这里的go function是在新的线程里面执行,而返回的结果可以到主线程中。 原文链接:https://www.f2er.com/go/189826.html

猜你在找的Go相关文章