Golang Basic - select and channel usage
2003 ワード
今日はGolangのtag,selectとchannelを勉強して、ここに記録しました!
1.tagの役割
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とchannelpackage 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は、新しいスレッドで実行され、返された結果はプライマリスレッドに返されます.