英文:
Why a pointer needs to be returned when the return type is actually error?
问题
我正在阅读文章《错误处理和Go》,但不太理解为什么在返回类型实际上是error的情况下,需要返回一个指针(&errorString{text})?
我的理解是error是一个接口,而errorString实现了这个接口,因此返回errorString也是可以的(但事实并非如此)。
// New返回一个格式为给定文本的错误。
func New(text string) error {
return &errorString{text}
}
errorString的实现如下:
// errorString是一个简单的错误实现。
type errorString struct {
s string
}
func (e *errorString) Error() string {
return e.s
}
文章链接:错误处理和Go
英文:
I am reading the article Error handling and Go, and don't quite understand why a pointer (&errorString{text}) has to be returned when the return type is actually error?
My understanding is error is an interface, and errorString implements the interface, therefore, return errorString is also okay (but it is not the case).
// New returns an error that formats as the given text.
func New(text string) error {
return &errorString{text}
}
errorString implementation
// errorString is a trivial implementation of error.
type errorString struct {
s string
}
func (e *errorString) Error() string {
return e.s
}
答案1
得分: 6
因为errorString类型的error接口是针对指针实现的(func (e *errorString) Error()),如果按照下面的方式实现,你将直接返回该值:
func (e errorString) Error() string {
return e.s
}
英文:
Because error interface for errorString is implemented for a pointer (func (e *errorString) Error()), if it was implemented like below you would return the value directly:
func (e errorString) Error() string {
return e.s
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论