Thanks! So the type's method receiver should be the deciding factor.
And method receivers for a type should be either *all* pointers or *all* 
values.

When deciding between method receivers, any advice on how to choose which 
to use?
Is it as simple as, when you need to change the instance pass a pointer, 
otherwise pass a value. And then once one method requires a pointer, then 
all methods should use a pointer. 

When given a type whose instance could be large, but it's methods do not 
require a pointer. Is it idiomatic to still pass a value in the constructor 
and all method receivers?

That's a good suggestion, using MakeT and NewT to further indicate return 
type.






On Friday, April 21, 2017 at 11:46:34 AM UTC-7, Alan Donovan wrote:
>
> On Friday, 21 April 2017 12:28:25 UTC-4, st ov wrote:
>>
>> In general, is it advisable to return pointers to newly constructed 
>> instances when using constructors?
>>
>> Would it matter more for types that don't have members of composite types 
>> slice and maps? 
>> So in the following example, https://play.golang.org/p/sWTWkHfZfB
>>
>> Bar is made up of mostly strings, so should return a pointer as those 
>> strings could be long.
>> While Foo is constructed of a slice and map, which are just references. 
>> So the constructor can return Foo as a value with little overhead.
>> And Qux has both a string and slice, but should return a pointer since 
>> the string can be large.
>> For interface Baz, returning a value is acceptable as its just a 
>> reference to Foo, Bar and Qux.
>>
>> Is that all correct? Or should I just always return a pointer? Any other 
>> advise?
>>
>
>  
> Let the receiver declarations of the type's methods guide you.  If the 
> methods of a type T have T as a receiver, you should generally pass values 
> of type T by copying them, either because the values are immutable (such as 
> a string, int, or perhaps a struct made up of immutable values) or because 
> T is or contains a reference such as a map or slice.  But if the type's 
> methods are associated with *T, then you should not copy values of type T 
> because this can violate the aliasing invariants of the type.  For example, 
> internally, a bytes.Buffer variable contains a pointer to itself, so 
> copying a value of type bytes.Buffer results in a new buffer that is 
> entangled with the original one.
>
> I usually suggest the name NewT for a function that returns a pointer to a 
> variable of type T, but MakeT for a function that returns a value of type 
> T, for consistency with the 'new' and 'make' built-in functions.
>

-- 
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