user1663023
user1663023

Reputation:

Pointer operator -> for golang

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.

Upvotes: 13

Views: 6492

Answers (4)

LaurentReese
LaurentReese

Reputation: 41

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.

Upvotes: 2

Paul Hankin
Paul Hankin

Reputation: 58349

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

Upvotes: 20

harold ramos
harold ramos

Reputation: 651

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

Upvotes: 0

Arjan
Arjan

Reputation: 21485

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.

Upvotes: 5

Related Questions