Why * prefix is not need for passed struct pointers?

Issue

I’ve stuck on understanding the pointer’s syntax. Here is my code:

package main

import "fmt"

type t struct{
    item int
}

func main(){

    x_struct := t{item:10}
    x_normal := 10;

    test(&x_normal, &x_struct)
}

func test(x_normal *int, x_struct *t){

    fmt.Println(*x_normal, x_struct.item)   // focus on this part
} 

When I execute go run main.go it runs correctly and prints 10 10. Ok, we’ve passed two parameters to the test function by address (using &). And I printed the *x_normal variable (by using a * prefix. But surprisingly accessing *x_struct.item throws the following error:

invalid operation: cannot indirect x_struct.item (variable of type int)

And I need to remove that * to make it work. The fun point is when I remove that * it works as expected and it’s still a pointer as well.

Why? Why should I use * to get the content of a variable and not use it to get the content of a strcut?

Solution

In the function test, x_struct is a pointer, and you can access the item using (*x_struct).item. Go compiler provides the shortcut x_struct.item.

*x_struct.item is not valid, because the redirection applies to x_struct.item in that case, which is not a pointer.

Answered By – Burak Serdar

Answer Checked By – Dawn Plyler (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.