2

Consider the following example: http://play.golang.org/p/eAot_sVwND

package main

import "fmt"

type Incrementor interface {
    Increment()
}

type Counter struct {
    i int

    Incrementor
}

func (c *Counter) Increment(){
    c.i++
} 

func main() {
    var c Incrementor
    c = &Counter{}
    c.Increment()
    fmt.Println(c)  
}

Unfortunatelly I need to c = &Counter{} because Counter.Increment() implementation has a pointer receiver otherwise c.Increment() calls won't be able to modify c.x property:

func (c Counter) Increment(){
    c.i++ // no errors, but now we increment c.x having a copy of c as context
}

How to make original implementation works without & on c = &Counter{}? In other words, how to avoid the need for the pointer receiver on C.Increment implementation at all?

This is just a nit, but I think that maybe a pointer is not necessary to do that in Go.

2 Answers 2

4

This is just a nit, but I think that maybe a pointer is not necessary to do that in Go.

Considering that Go uses to pass everything by value, a pointer receiver is the natural way to achieve what you want.
This is supported by the Go FAQ:

First, and most important, does the method need to modify the receiver? If it does, the receiver must be a pointer.

You would find a similar conclusion in "Things I Wish Someone Had Told Me About Golang: pointers"

Sign up to request clarification or add additional context in comments.

3 Comments

So there is no way to get rid of the & &Counter{} initialization?
Motive for this concern is that I find it quite unpleasant to initialize structs by reference when using tirhd party packages, so I try to avoid it as much as possible. You end never knowing how to initialize things until you see a compile error.
@marcioAlmada I understand, but I don't know of a natural way to avoid pointer intialization in Go, when you have a method which modifies its content.
2

You could consider defining an NewCounter function that encapsulates the initialization of your type (or some 3rd party) and returns a *Counter. Usage could look something like this:

func main() {
    c := NewCounter()
    c.Increment()
    fmt.Println(c)  
}

1 Comment

Nice, we see this pattern all over the place within go std libs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.