Is this a context leak or just a false positive from the linter

Viewed 19

Here is a simplified version of what I was doing in another code base:

package main

import (
    "context"
    "time"
)

func test() {

    var cancel context.CancelFunc
    var ctx context.Context

    defer func() {
        if cancel != nil {
            cancel()
        }
    }()

    ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(time.Second))

    <-ctx.Done()

    cancel()

    ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(time.Millisecond*500))

    <-ctx.Done()
}

func main() {
    test()
}

If the function named test, a defer statement exists to invoke the context's cancel function when it exits.

Then later in the function, I explicitly invoke cancel() to clean up the first context and create another context and cancel pair and reassign to the same variables.

VS Code lights up this second context.WithDeadline statement with a linter warning:

the cancel function is not used on all paths (possible context leak)lostcancel

And the closing brace at the end of the function has a similar warning:

this return statement may be reached without using the cancel var defined on line 25 lostcancel

Picture of VS Code warning:

enter image description here

This was surprising, because my assumption is that the defer statement will invoke cancel() on the second instance.

Is this a false positive, or do I have a misunderstanding of how variables are captured in local function declarations like the defer statement I am using?

Either way, the linter warning is resolved by explicitly invoking cancel again.

0 Answers
Related