Specify a point in the Golang

I found an error while implementing the code below:

package main import ( "fmt" ) type Struct struct { a int b int } func Modifier(ptr *Struct, ptrInt *int) int { *ptr.a++ *ptr.b++ *ptrInt++ return *ptr.a + *ptr.b + *ptrInt } func main() { structure := new(Struct) i := 0 fmt.Println(Modifier(structure, &i)) } 

This gives me an error something about "invalid indirect ptr.a (type int) ...". And also why does the compiler not give me an error about ptrInt? Thanks in advance.

+8
pointers go
source share
1 answer

Just do

 func Modifier(ptr *Struct, ptrInt *int) int { ptr.a++ ptr.b++ *ptrInt++ return ptr.a + ptr.b + *ptrInt } 

In fact, you tried to use ++ on *(ptr.a) , and ptr.a is an int, not a pointer to an int.

You could use (*ptr).a++ , but this is not necessary since Go will automatically ptr.a if ptr is a pointer, so you don't have -> in Go.

+13
source share

All Articles