加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang Basic - select and channel usage

发布时间:2020-12-16 18:32:03 所属栏目:大数据 来源:网络整理
导读:今天学习了一下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"`Pass

今天学习了一下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是在新的线程里面执行,而返回的结果可以到主线程中。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读