Hello st ov
What do you mean with "even though a value receiver would be acceptable" ?
Your sample code clearly shows that after foo.SetVal(1) , we still have foo.val 
== 0  which looks unacceptable to me (broken setter).

Is it possible that you are confusing  "is the method receiver a reference 
type" with "are the method arguments reference types" ?
In any case, when you want your method to modify the receiver, you *must* 
use a reference receiver (i.e. pointer), doing otherwise would be pointless 
(modifying a copy, which would immediately be discarded when method 
returns).

If you wonder about passing value arguments (e.g.  val int) or reference 
arguments (e.g.  ref []int) : both are possible and may be mixed.  But this 
is mostly unrelated to the pointerness of the receiver.

HTH
 Val

On Saturday, March 25, 2017 at 2:20:06 AM UTC+1, st ov wrote:
>
> Is it idiomatic to mix-&-match pointer and value method receivers for a 
> given type? 
> or in *general*, if a single method requires a pointer receiver than *all 
> methods* should take a pointer, regardless if a value receiver is 
> appropriate?
>
> For example, should Foo.SetVal also be a pointer receiver even though a 
> value receiver would be acceptable?
> https://play.golang.org/p/rd_6BLol8O
>
> type Foo struct{
>     ref []int
>     val int
> }
>
> // would not set if method receiver is value receiver (foo Foo)
> func (foo *Foo) SetRef(ref []int) {
>     foo.ref = ref
> }
> func (foo Foo) SetVal(val int) {
>     foo.val = val
> }
>
> func main() {
>     foo := Foo{}
>     foo.SetRef([]int{1,2,3})
>     foo.SetVal(1)
>     
>     fmt.Printf("%v",foo) // {[1 2 3] 0}
> }
>
>
>
>

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