Skip to content

Commit cb86b52

Browse files
committed
add notes on using function literals, go routines and using clearer syntax for for loops when waiting for channel updates
1 parent ee02b74 commit cb86b52

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

go-course.md

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -581,9 +581,49 @@ for l := range c {
581581
}
582582
```
583583
584+
### sleeping a routine
585+
586+
Important. If the main routine is `Sleep`ed, nothing else (including other go
587+
routines) will complete - they will be queued up to wait for the main routine to
588+
begin again. `time.Sleep` should really only be used on child go routines unless
589+
the desired outcome is for the whole application to cease activity.
590+
591+
the following will sleep the go routine for 5 seconds
592+
593+
```
594+
time.Sleep(5 * time.Second)
595+
```
596+
597+
### using a function literal for go routines
598+
599+
we can use a function literal (think anonymous function) to kick off a go
600+
routine
601+
602+
```
603+
for link := range myChannel {
604+
go func (l string) {
605+
time.Sleep(5 * time.Second)
606+
checkLink(l, myChannel)
607+
}(link)
608+
}
609+
```
610+
611+
notes:
612+
613+
* the function literal has to self-execute by using parentheses after the
614+
declaration
615+
* because `link` in the outer `for` loop scope may be changing every iteration,
616+
we need to copy the value into the function literal
617+
* the string `link` is passed to the function literal via the parentheses as
618+
it would be with a function declaration
619+
* `checkLink()` is no longer kicking off the go routine - the function literal
620+
is
621+
584622
lectures:
585623
586-
* https://www.udemy.com/course/go-the-complete-developers-guide/learn/lecture/7809266#questions
624+
* https://www.udemy.com/course/go-the-complete-developers-guide/learn/lecture/7809266
625+
* https://www.udemy.com/course/go-the-complete-developers-guide/learn/lecture/7809272
626+
* https://www.udemy.com/course/go-the-complete-developers-guide/learn/lecture/7824514
587627
588628
repos:
589629

0 commit comments

Comments
 (0)