title: Understanding Golang Context timeout
body: <p>I am having trouble understanding how I can check if context exceeded deadline set by timeout, or if I should check at all?</p>
  <p>This is a snippet from mongo-go-driver:</p>
  <pre><code>client, err := NewClient(&quot;mongodb://foo:bar@localhost:27017&quot;)
  if err != nil { return err }
  ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  defer cancel()
  err = client.Connect(ctx)
  if err != nil { return err }
  </code></pre>
  <p>Reading this code, how do I know if context exceeded deadline? From what I naively understand (or not understand), the line <code>err = client.Connect(ctx)</code> will give me error including deadline exceeded (if exceeded), thus I think I don't even need to explicitly check?</p>
  <p>But then while looking around the internet to better understand how contexts work, I come across uses of select cases which explicitly checks contexts as below (code snippet from <a href="http://p.agnihotry.com/post/understanding_the_context_package_in_golang/" rel="nofollow noreferrer">http://p.agnihotry.com/post/understanding_the_context_package_in_golang/</a>):</p>
  <pre><code>//Use a select statement to exit out if context expires
    select {
    case &lt;-ctx.Done():
      fmt.Println(&quot;sleepRandomContext: Time to return&quot;)
    case sleeptime := &lt;-sleeptimeChan:
      //This case is selected when processing finishes before the context is cancelled
      fmt.Println(&quot;Slept for &quot;, sleeptime, &quot;ms&quot;)
    }
  </code></pre>
  <p>Should I be explicitly checking for it? If not, when should I use explicit checks?</p>