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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值