使用 oklog/run 来自 Go 编译器的错误“(无值)用作值”

我正在研究oklog/run包的一个简单示例,并且在尝试返回错误日志时在 VS Code 中看到此编译错误:

log.Errorf("abnormal termination: %s", err) (no value) used as value

在 group.Run 的描述中说

“..Run 仅在所有 actor 退出时返回。Run 返回第一个退出的 actor 返回的错误。”

我想知道这是否与它有关,比如它无法使用当前不存在的错误进行编译,因为 run.Group 尚未全部返回?

感谢您提供的任何帮助。

代码:

package main


import (

    "context"

    "time"


    "github.com/oklog/run"

    "github.com/pkg/errors"

    log "github.com/sirupsen/logrus"

)


func logAForever(ctx context.Context) {

    for {

        select {

        case err := <-ctx.Done():

            log.Error(err)

            return

        default:

            log.Info("A")

            time.Sleep(1 * time.Second)

        }

    }

}


func logBFor10Sec(ctx context.Context) {

    for i := 1; i < 10; i++ {

        log.Info("B")

        time.Sleep(1 * time.Second)

    }

}


func main() {

    ctx, testStopFunc := context.WithCancel(context.Background())


    var group run.Group


    group.Add(func() error {

        log.Info("First actor added to run group. Starting execute function...")

        logAForever(ctx)

        return nil

    }, func(error) {

        log.Info("The first interrupt function was invoked.")

        testStopFunc()

        time.Sleep(100 * time.Millisecond)

    })


    group.Add(func() error {

        log.Info("Second actor added to run group. Starting execute function...")

        logBFor10Sec(ctx)

        return nil

    }, func(error) {

        log.Info("The second interrupt function was invoked.")

        testStopFunc()

        time.Sleep(100 * time.Millisecond)

    })


    if err := group.Run(); !errors.As(err, &run.SignalError{}) {

        // return

        return log.Errorf("abnormal termination: %s", err)

    }


}


浮云间
浏览 73回答 1
1回答

慕容森

log.Errorf不返回任何值,但您正试图通过return关键字返回它。请尝试使用此代码:if err := group.Run(); !errors.As(err, &run.SignalError{}) {&nbsp; log.Errorf("abnormal termination: %s", err)&nbsp; return}
打开App,查看更多内容
随时随地看视频慕课网APP