also, you might think a simpler implementation could be

type errorString string

func (s *errorString) Error() string {
    return string(*s)
}

func New(msg string) error {
    return (*errorString)(&msg)
}

but that would allow reflection to change the string.

On Sat, Dec 10, 2016 at 11:12 PM, Axel Wagner <axel.wagner...@googlemail.com
> wrote:

>
>
> On Sat, Dec 10, 2016 at 8:10 PM, Jon <jonathan.gill...@gmail.com> wrote:
>
>> I would like to know what my default practice should be when returning
>> structs from functions. Should I return a value or a pointer? (Assume I
>> don't need the functionality of returning a pointer and my struct contains
>> at most one simple field so a vast copy isn't needed if I return a value.)
>>
>> A specific example could be the errors package
>> <https://golang.org/src/errors/errors.go> with errors.New.
>>
>> The New function is implemented by returning an errorString pointer:
>> <https://play.golang.org/p/WPmP8ZVS0_>
>>
>> func New(text string) error {
>>     return &errorString{text}
>> }
>>
>> Could it just as easily have been implemented by returning an errorString
>> value <https://play.golang.org/p/Gawy-mgw2X>? If so why was the pointer
>> return chosen over value return?
>>
>
> Because that way
> errors.New("foo") != errors.New("foo")
> This means, that if two packages were to define errors with the same
> message by coincidence, they wouldn't get mixed up.
>
>
>> func New(text string) error {
>>     return errorString{text}
>> }
>>
>> Could it also have been implemented as below
>> <https://play.golang.org/p/H2NIARHO-Y> which looks even simpler?
>>
>> func New(text string) error {
>>     return errorString(text)
>> }
>> // errorString is a trivial implementation of error.
>> type errorString string
>>
>> func (e errorString) Error() string {
>>     return string(e)
>> }
>>
>> What was the thought process that went into the implementation of the
>> errors package? Were the latter two implementation options I suggest
>> considered? If so why were they disregarded? Performance? Coding standards?
>> Heap allocation benefits?
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "golang-nuts" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to golang-nuts+unsubscr...@googlegroups.com.
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to