面试题答案
一键面试package main
import (
"fmt"
"time"
)
func networkRequest(ch chan string) {
// 模拟网络请求
time.Sleep(3 * time.Second)
ch <- "response"
}
func main() {
ch := make(chan string)
go networkRequest(ch)
var timeoutTime time.Time
select {
case res := <-ch:
fmt.Println("Received: ", res)
case <-time.After(2 * time.Second):
timeoutTime = time.Now()
fmt.Printf("Timeout at %v\n", timeoutTime)
// 这里可以将超时时间等信息记录到日志文件或者数据库等进行后续分析
}
}