Golang Basic - select and channel usage

Golang Basic - select and channel usage,第1张

概述今天学习了一下Golang 的 tag,select 和 channel ,记录在此! 1.tag 的作用 package mainimport ( "encoding/json" "fmt" "reflect")type Accout struct { UserId int `json:"user_id" bson:"user_id"` UserName strin

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

1.tag 的作用

package mainimport (	"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_IDuser_IDuser_nameuser_namepass_wordpass_word
2.select 和 channel

package mainimport (	"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是在新的线程里面执行,而返回的结果可以到主线程中。 总结

以上是内存溢出为你收集整理的Golang Basic - select and channel usage全部内容,希望文章能够帮你解决Golang Basic - select and channel usage所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1284649.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-09
下一篇 2022-06-09

发表评论

登录后才能评论

评论列表(0条)

保存