gpt4 book ai didi

go - 期待 nil 但得到一个 nil 值的接口(interface)作为返回,这应该是 nil

转载 作者:IT王子 更新时间:2023-10-29 01:51:26 26 4
gpt4 key购买 nike

运行时间 https://play.golang.org/p/sl12vfS9vP

package main

import "fmt"

func main() {
err := run()
if err != nil {
fmt.Printf("%#v", err)
}
}

func run() (err error) {
return check()
}

func check() *Result {
return nil
}

type Result struct {
message string
}

func (result *Result) Error() string {
return result.message
}

最佳答案

这是在 FAQ 上讨论的和 Go Traps网站:

An interface value is nil only if the inner value and type are both unset, (nil, nil). In particular, a nil interface will always hold a nil type. If we store a pointer of type *int inside an interface value, the inner type will be *int regardless of the value of the pointer: (*int, nil). Such an interface value will therefore be non-nil even when the pointer inside is nil.

(...)

To return a proper nil error to the caller, the function must return an explicit nil:

func returnsError() error {
if bad() {
return ErrBad
}
return nil
}

关于go - 期待 nil 但得到一个 nil 值的接口(interface)作为返回,这应该是 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26845572/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com