gpt4 book ai didi

go - 返回 &obj 是什么意思?对等式检查有什么影响

转载 作者:数据小太阳 更新时间:2023-10-29 03:40:16 25 4
gpt4 key购买 nike

返回有什么区别

func New(text string) error { return &errorString{text} }

或返回喜欢

func New(text string) error { return errorString{text} }

errorString 定义如下

type errorString struct { text string }

错误定义如下

type error interface {
Error() string
}

特别想知道返回值有什么区别:

return &errorString{text}
vs.
return errorString{text}

我已经阅读了指南,但没有提到区别。它只提到,对于错误对象,您不能使用等于您不想要的东西。

最佳答案

errorString{text} 是一个结构,&errorString{text} 是一个指向结构的指针。参见 https://tour.golang.org/moretypes/1有关这意味着什么的更详细解释。

还有这个问题具体说明了何时返回:Pointers vs. values in parameters and return values .返回 errorText{text} 返回整个结构的副本,而 &errorText{text} 返回指向结构的指针。

结构 S 和指向类型 S 的结构的指针在 Go 中是两种不同的类型。 errorText 要实现 error 接口(interface),errorText 必须实现 Error() string 方法,但它也需要具有正确的接收器类型。

例如,这是可以的:

type errorText struct {
text string
}

func (e errorText) Error() string { return e.text }

func SomethingThatReturnsYourError() error {
return errorText{"an error"}
}

这也行:

type errorText struct {
text string
}

func (e errorText) Error() string { return e.text }

func SomethingThatReturnsYourError() error {
return &errorText{"an error"} // Notice the &
}

但这不行,编译器会报错:

type errorText struct {
text string
}

// notice the pointer receiver type
func (e *errorText) Error() string { return e.text }

func SomethingThatReturnsYourError() error {
return errorText{"an error"}
}

错误消息:不能使用 errorString 文字(类型 errorString)作为返回参数中的类型错误:
errorString 没有实现错误(错误方法有指针接收者)

为了使用指针接收器,你必须返回一个指针:

type errorText struct {
text string
}

func (e *errorText) Error() string { return e.text }

func SomethingThatReturnsYourError() error {
return &errorText{"an error"}
}

关于go - 返回 &obj 是什么意思?对等式检查有什么影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57878878/

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