Standard library / context

context.WithTimeoutCause()

Derive a timeout and attach a custom cause for expiration, not manual cancellation. Expected stdout: 'budget\n'.

Formal Syntax & Structure

go syntaxgo
func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc)

Parameters & Attributes

NameTypeDescription
parentContextNon-nil parent context.
timeouttime.DurationDuration until cancellation.
causeerrorError to record when the specified deadline expires.

Return Value

(Context, CancelFunc)

Derived context and cancel function.

Working Example

Example Snippetgo
package main
import (  "context"  "errors"  "fmt")
func main() {  ctx, cancel := context.WithTimeoutCause(context.Background(), 0, errors.New("budget"))  defer cancel()  <-ctx.Done()  fmt.Println(context.Cause(ctx))}
Go Reference