Метод Search параллельно запрашивает Storage.Items и Storage.Tags в двух горутинах, отправляет ошибки в канал errs и собирает items с их тегами вложенным циклом. Рабочий ли это код? Перепишите.
Как на собесе: 15 минут, ищи всё — гонки, утечки, ошибки, безопасность, стиль. Ссылайся на строки.
1 type Storage interface { 2 Items ( ids [ ] string ) ( [ ] * Item , error ) 3 Tags ( ctx context . Context , ids [ ] string ) ( [ ] * Tag , error ) 4 } 5 6 type Item struct { 7 ID int 8 Created uint8 9 } 10 11 type Tag struct { 12 ItemID int 13 Low float64 14 High float64 15 } 16 17 type ItemWithTags struct { 18 ID int 19 Tags [ ] * Tag 20 } 21 22 type GetReq struct { 23 IDs [ ] string 24 } 25 26 type GetResp struct { 27 Items [ ] * ItemWithTags 28 } 29 30 type Server struct { 31 storage Storage 32 } 33 34 func ( s Server ) Search ( ctx context . Context , req GetReq ) ( * GetResp , error ) { 35 var errs chan error 36 37 var items [ ] * Item 38 go func ( ) { 39 res , e : = s . storage . Items ( req . IDs ) 40 if e ! = nil { 41 errs < - e 42 return 43 } 44 45 items = res 46 } ( ) 47 48 var tags [ ] * Tag 49 go func ( ) { 50 res , e : = s . storage . Tags ( context . Background ( ) , req . IDs ) 51 if e ! = nil { 52 errs < - e 53 return 54 } 55 56 tags = res 57 } ( ) 58 59 for e : = range errs { 60 if e ! = nil { 61 return nil , e 62 } 63 } 64 65 out : = [ ] * ItemWithTags { } 66 67 for _ , item : = range items { 68 for _ , tag : = range tags { 69 if tag . ItemID = = item . ID { 70 out = append ( out , & ItemWithTags { ID : item . ID , Tags : [ ] * Tag { tag } } ) 71 } 72 } 73 } 74 75 return & GetResp { Items : out } , nil 76 } Найденные проблемы Проверить Не знаю — покажи ответ ⌘ Enter — проверить