Interview - Golang

General Problems

What is a goroutine? how to stop it?

a goroutine is a go-defined, user-space, light-weight thread(different from pthread from linux).

we have to use signal to stop a goroutine

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
func main() {
  stop := make(chan bool)
  go func() {
    for {
      select {
        case <-stop:
          return
        default:
          fmt.Println("working...")
          time.Sleep(5000)
      }
    }
  }()

  ...
  stop <- true
}

What should be taken care of when we use channel

  • sending/receiving data to a nil-channel, both will be blocked forever
  • sending data to a closed channel will panic
  • receiving data from a closed channel, if the buffer is empty, would return a zero-value

  • buffered channel is async
  • no-buffer channel is sync

the difference between new and make

  • func new(Type) *Type
    • use new to assign memory
    • new requires a type, not a value
    • the return value is the pointer to the new created memory block
  • func make(Type, size IntegerType) Type
    • make is used to initialize slice, map, chan, and return reference
Get Things Done
Built with Hugo
Theme Stack designed by Jimmy