Whats wrong with my builder pattern

97 views
Skip to first unread message

Денис Мухортов

unread,
Dec 6, 2021, 1:46:50 AM12/6/21
to golang-nuts
I have 2 empty strings in the output. But why?
https://play.golang.com/p/v7zEVBM17YH

Reto

unread,
Dec 6, 2021, 2:01:11 AM12/6/21
to Денис Мухортов, golang-nuts
Hi,

https://go.dev/doc/faq#methods_on_values_or_pointers

>First, and most important, does the method need to modify the receiver? If it does, the receiver must be a pointer. (Slices and maps act as references, so their story is a little more subtle, but for instance to change the length of a slice in a method the receiver must still be a pointer.) In the examples above, if pointerMethod modifies the fields of s, the caller will see those changes, but valueMethod is called with a copy of the caller's argument (that's the definition of passing a value), so changes it makes will be invisible to the caller.

You have a non pointer receiver, you modify a copy.

Cheers,
Reto

Tyler Compton

unread,
Dec 6, 2021, 2:01:49 AM12/6/21
to Денис Мухортов, golang-nuts
It's because your method receivers are values, not pointers:

func (b Builder) setFirst() {
    b.firstElement = "First element"
}


In Go, method receivers work a lot like regular function arguments. When you call the above method, you're operating on a copy of the Builder struct. Any time you pass an argument by value like this, its value is copied. What you probably want is to define the method on a pointer receiver:

func (b *Builder) setFirst() {
    b.firstElement = "First element"
}

Now, when you call this method on an object, only the pointer is copied. Inside the method, you're referring to the same Builder instance that you are when calling the method.

On Sun, Dec 5, 2021 at 10:47 PM Денис Мухортов <muhorto...@gmail.com> wrote:
I have 2 empty strings in the output. But why?
https://play.golang.com/p/v7zEVBM17YH

--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/4060a981-f43c-49ec-92f7-849ab23d1ea9n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages