I has encountered an error while implement the below code:
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))
}
That gives me an error something about "invalid indirect of ptr.a (type int)...". And also why the compiler don't give me error about ptrInt? Thanks in advance.
Just do
func Modifier(ptr *Struct, ptrInt *int) int {
ptr.a++
ptr.b++
*ptrInt++
return ptr.a + ptr.b + *ptrInt
}
You were in fact trying to apply ++
on *(ptr.a)
and ptr.a
is an int, not a pointer to an int.
You could have used (*ptr).a++
but this is not needed as Go automatically solves ptr.a
if ptr
is a pointer, that's why you don't have ->
in Go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With