我正在探索 Go 并尝试使用通道建立一种管道。我只想在 main() 中读取一些内容并将它们发送到 process() 进行处理,在这种情况下只需将值打印到屏幕上。
不幸的是,在下面的代码中, process() 似乎从不从通道读取,或者至少它不打印任何内容;我究竟做错了什么?
package main
import ( "fmt" ; "database/sql" ; _ "github.com/lib/pq" ; "time" ; "gopkg.in/redis.v3" )//; "strconv" )
type Record struct {
userId, myDate int
prodUrl string
}
func main(){
//connect to db
db, err := sql.Open(...)
defer db.Close()
//error check here...
//exec query
rows, err := db.Query("select userID,url,date from mytable limit 10")
defer rows.Close()
//error check here...
//create channel to buffer rows read
bufferChan := make(chan *Record,1000)
go process(bufferChan)
//iterate through results and send them to process()
row := new(Record)
for rows.Next(){
err := rows.Scan(&row.userId, &row.prodUrl, &row.myDate)
bufferChan <- row
fmt.Printf("row sent %v",row.userId)
}
}
//prints Record values
func process (buffer chan *Record) {
row := <- buffer
fmt.Printf("row received: %d %v %d ", row.userId,row.prodUrl,row.myDate)
}
手掌心
qq_遁去的一_1
汪汪一只猫
相关分类