Strange int behavior inside a structure

Let's say we have such a structure (one of the simplest):

type some struct{
    I uint32
}

And we want to have a variable of this type and atomically increase the cycle (maybe in another version of goroutine, but now the story is different). I do the following:

q := some{0}
for i := 0; i < 10; i++ {
        atomic.AddUint32(&q.I,1) // increment [1]
        fmt.Println(q.I)
}

We get what we expect so well, but if we declare a function for this type as follows:

func (sm some) Add1(){
    atomic.AddUint32(&sm.I,1)
}

and call this function in the above example (line [1]), the value does not increase and we get only zeros. The question is obvious - why?

This should be something basic, but since I'm new, I don't get it.

+4
source share
2 answers

Go programming language specification

Calls

. , . , .

sm some , . .

,

package main

import (
    "fmt"
    "sync/atomic"
)

type some struct {
    I uint32
}

func (sm *some) Add1() {
    atomic.AddUint32(&sm.I, 1)
}

func main() {
    var s some
    s.Add1()
    fmt.Println(s)
}

:

{1}

(FAQ)

?

C, Go . , , , , . , int int, , , .

?

func (s *MyStruct) pointerMethod() { } // method on pointer
func (s MyStruct)  valueMethod()   { } // method on value

, , , . (s ) , . , , . .

-, , ? , . ( , , , , .) , pointerMethod s, , valueMethod ( ), , , .

, Java, Java ; Go's .

-, . , , , .

. , , , . . .

, , , , , , .

+7

, , , , .

package main

import (
"sync/atomic"
"fmt"
)

type some struct{
    I uint32
}

func main() {
q := &some{0}
for i := 0; i < 10; i++ {
        q.Add1()
        fmt.Println(q.I)
}
}

func (sm *some) Add1(){
    atomic.AddUint32(&sm.I,1)
}
+2

All Articles