Standard library / context
context.WithTimeout()
Derive a deadline relative to the current time; the parent may impose an earlier deadline. Expected stdout: 'context deadline exceeded\n'.
Formal Syntax & Structure
go syntaxgo
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| parent | Context | Non-nil parent context. |
| timeout | time.Duration | Duration until cancellation. |
Return Value
(Context, CancelFunc)
Derived context and cancel function.
Working Example
Example Snippetgo
package main
import ( "context" "fmt")
func main() { ctx, cancel := context.WithTimeout(context.Background(), 0) defer cancel() <-ctx.Done() fmt.Println(ctx.Err())}