Goroutines and loop together in Golang π₯°
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
for i := 0; i < fanout; i++ { go func() { for { c.Dec(19) time.Sleep(300e6) } }() go func() { for { c.Inc(47) time.Sleep(400e6) } }() } |
Check if sum of numbers are equal π
1 2 3 |
func sumEqual(u, v, w float64) bool { return (u+v == w) && (u == w-v) && (v == w-u) } |
Factory Method Pattern In Golang π
1 2 3 4 5 6 7 8 9 |
func getTransport(tt string) (iTransport, error) { if tt == "scooter" { return newElectricScooter(), nil } if tt == "quadcopter" { return newQuadcopter(), nil } return nil, fmt.Errorf("Wrong type") } |
How to check if empty name in Golang multi languages π
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
func (svc *UserSvc) isEmptyName(name model.User_Name) bool { if name.First.RU == "" { if name.First.EN == "" { if name.First.TR == "" { if name.First.IT == "" { if name.Last.RU == "" { if name.Last.EN == "" { if name.Last.TR == "" { if name.Last.IT == "" { return true } } } } } } } } return false } |
Defer and sleep in Golang π
1 2 3 4 5 6 |
func GetUser() *User { defer func() { time.Sleep(100 * time.Millisecond) }() return &User{} } |
Nice error handling in Golang π€£
1 2 3 4 5 6 7 8 9 |
func (c *Client) DeleteFile(filename string) { _, err := s3.New(c.session).DeleteObject(&s3.DeleteObjectInput{ Bucket: aws.String(c.bucket), Key: aws.String(filename), }) if err != nil { return } } |
Very informative variables in nested loop π ok -> okk -> okkk ....It might be okkkkkkkkkkkkkkkkkkkkkkkkkkkk in the end π
1 2 3 4 5 6 7 8 9 10 11 12 |
if user, ok := db.User[userId]; ok { for _, cardId := range user.CardIds { if card, okk := db.Card[cardId]; okk { if notif, okkk := db.Notif[card.NotifId]; okkk { card_notifs = append(card_notifs, CardNotif{card.Id, card, notif}) } } } c.JSON(http.StatusOK, card_notifs) } else { c.String(http.StatusNotFound, "") } |