优化ErrGroup结果切片的定义

This commit is contained in:
wangwenbin 2023-12-28 17:46:49 +08:00
parent e57918df05
commit 9fce7acead

View File

@ -47,13 +47,13 @@ func GetAllCityWeatherData(timeOut time.Duration) ([]*WeatherData, error) {
// 创建一个携带cancel的context
ctx, cancel := context.WithTimeout(context.Background(), timeOut)
defer cancel() // 确保所有路径都调用cancel
list := make([]*WeatherData, 0)
// 初始化一个ErrGroup对象
g, ctx := errgroup.WithContext(ctx)
// 城市列表
cities := []string{"New York", "Tokyo", "Berlin", "Paris", "Beijing"}
list := make([]*WeatherData, 0, len(cities))
// 循环启动goroutine来获取每个城市的天气数据
for _, city := range cities {