Rule for Go Pointers, References, Dereferencing:

后端 未结 1 759
野的像风
野的像风 2021-01-01 05:27

I am new to GoLang, coming from the Delphi, C++ world - admittedly very excited about this language, which I think is destined to become \"the next big thing\".

I am

相关标签:
1条回答
  • 2021-01-01 06:00

    All of the methods for a List have *List receivers: (http://golang.org/pkg/container/list/)

    func (l *List) Back() *Element
    func (l *List) Front() *Element
    func (l *List) Init() *List
    ...
    func (l *List) Remove(e *Element) interface{}
    

    In your example l is of type *List, so there's no need to dereference them.

    Suppose, instead, that you had something like this:

    type A struct{}
    func (a  A) X() {
        fmt.Println("X")
    }
    func (a *A) Y() {
        fmt.Println("Y")
    }
    

    You are allowed to write:

    a := A{}
    a.X()
    a.Y() // == (&a).Y()
    

    Or you can do the following:

    a := &A{}
    a.X() // same like == (*a).X()
    a.Y()
    

    But it only works for method receivers. Go will not automatically convert function arguments. Given these functions:

    func A(x *int) {
        fmt.Println(*x)
    }
    func B(y int) {
        fmt.Println(y)
    }
    

    This is invalid:

    A(5)
    

    You have to do this:

    var x int 
    A(&x)
    

    This is also invalid:

    var y *int
    B(y)
    

    You have to do this:

    B(*y)
    

    Unlike C# or Java, when it comes to structs, Go does not make a distinction between reference and value types. A *List is a pointer, a List is not. Modifying a field on a List only modifies the local copy. Modifying a field on a *List modifies all "copies". (cause they aren't copies... they all point to the same thing in memory)

    There are types which seem to hide the underlying pointer (like a slice contains a pointer to an array), but Go is always pass by value.

    0 讨论(0)
提交回复
热议问题