doutuo1939 2016-03-05 12:57
浏览 111
已采纳

结构体中int的奇怪行为

Let's say we have this kind of a struct (one of the simplest ever):

type some struct{
    I uint32
}

And we want to have a variable of that type and to atomically increment in for loop (possibly in another 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're getting what we'd expect, so far so good, but if we declare a function for that type as follows:

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

and call this function in the above sample (line [1]) the value isn't incremented and we just get zeros. The question is obvious - why?

This has to be something basic but since I am new to go I don't realize it.

  • 写回答

2条回答 默认 最新

  • doq70020 2016-03-05 13:02
    关注

    The Go Programming Language Specification

    Calls

    In a function call, the function value and arguments are evaluated in the usual order. After they are evaluated, the parameters of the call are passed by value to the function and the called function begins execution. The return parameters of the function are passed by value back to the calling function when the function returns.

    The receiver sm some is passed by value to the method and the copy is discarded when you return from the method. Use a pointer receiver.

    For example,

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

    Output:

    {1}
    

    Go Frequently Asked Questions (FAQ)

    When are function parameters passed by value?

    As in all languages in the C family, everything in Go is passed by value. That is, a function always gets a copy of the thing being passed, as if there were an assignment statement assigning the value to the parameter. For instance, passing an int value to a function makes a copy of the int, and passing a pointer value makes a copy of the pointer, but not the data it points to.

    Should I define methods on values or pointers?

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

    For programmers unaccustomed to pointers, the distinction between these two examples can be confusing, but the situation is actually very simple. When defining a method on a type, the receiver (s in the above examples) behaves exactly as if it were an argument to the method. Whether to define the receiver as a value or as a pointer is the same question, then, as whether a function argument should be a value or a pointer. There are several considerations.

    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.

    By the way, pointer receivers are identical to the situation in Java, although in Java the pointers are hidden under the covers; it's Go's value receivers that are unusual.

    Second is the consideration of efficiency. If the receiver is large, a big struct for instance, it will be much cheaper to use a pointer receiver.

    Next is consistency. If some of the methods of the type must have pointer receivers, the rest should too, so the method set is consistent regardless of how the type is used. See the section on method sets for details.

    For types such as basic types, slices, and small structs, a value receiver is very cheap so unless the semantics of the method requires a pointer, a value receiver is efficient and clear.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路