12

It seems golang does not have the pointer operator -> as C and C++ have. Now let's say I have a function looks something like this: myfun(myparam *MyType), inside the function, if I want to access the member variables of MyType, I have to do (*myparam).MyMemberVariable. It seems to be a lot easier to do myparam->MyMemberVariable in C and C++.

I'm quite new to go. Not sure if I'm missing something, or this is not the right way to go?

Thanks.

4 Answers4

19

In Go, both -> and . are represented by .

The compiler knows the types, and can dereference if necessary.

package main

import "fmt"

type A struct {
    X int
}

func main() {
    a0, a1 := A{42}, &A{27}
    fmt.Println(a0.X, a1.X)
}
Uclydde
  • 1,414
  • 3
  • 16
  • 33
Paul Hankin
  • 54,811
  • 11
  • 92
  • 118
  • Thanks for the answer. My real questions is os.Lstat(path string) claims to return os.FileInfo, however, the os.Lstat implementation actually returned &fileStat{...}, which I believe is a pointer. os.FileInfo is an interface, however, Lstat returns a pinter type of os.fileStat which implements os.FileInfo. I'm wondering whether it is true that in go, it is ok to replace a interface type with a pointer type? I'm really confused. –  Jan 27 '14 at 18:20
  • 3
    Perhaps clarify your thoughts, then ask a second question? – Paul Hankin Jan 27 '14 at 18:25
  • 1
    It all boils down to what (pointer or the raw type) implements the method. If the pointer receiver has the required methods, then it's perfectly to return the pointer where an interface is required. – justinas Jan 27 '14 at 18:49
5

You can do myparam.MyMemberValue, pointers are automatically dereferenced

Go spec:

Selectors automatically dereference pointers to structs. If x is a pointer to a struct, x.y is shorthand for (x).y; if the field y is also a pointer to a struct, x.y.z is shorthand for ((*x).y).z, and so on. If x contains an anonymous field of type *A, where A is also a struct type, x.f is shorthand for (*x.A).f.

Arjan
  • 19,957
  • 2
  • 55
  • 48
2

Hummm, this automatic dereferencing can be very confusing (for old programmers like me)

  1. If you learn programmation with GOLANG, no problem, it is practical.
  2. If you pass from C to GOLANG, this will seem strange, you will probably prefer (at the beginning at least) to keep the "(*my_var).my_field" expression instead of "my_var.myfield"
  3. If you pass from GOLANG to C, you will get many compilation errors.
0
Goes uses -> for passing data by using channels.

package main

import "fmt"

type Person struct {
    Name string
}

func (p *Person) printName() {
    p.Name = "brian"
}

func main() {
    // obj
    brian := Person{""}

    // prints obj default value
    fmt.Println("No pointer", brian.Name) 

    // it access the method with the pointer
    brian.printName()

    // prints the result 
    fmt.Println("With a pointer", brian.Name)
}
harold ramos
  • 639
  • 7
  • 6