Go   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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 @R_450_10495@ng `json:"user_name" bson:"user_name"`
	password @R_450_10495@ng `json:"pass_word" bson:"pass_word"`
}

func main() {
	account := &Accout{UserId: 1,UserName: "jusTin",password: "12345"}
	accountJson,_ := json.Marshal(account)
	fmt.Println(@R_450_10495@ng(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 @R_450_10495@ng,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所遇到的程序开发问题。

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

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。