Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Point to Struct in Golang

Tags:

pointers

go

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.

like image 641
Coder Avatar asked Oct 17 '12 09:10

Coder


1 Answers

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.

like image 122
Denys Séguret Avatar answered Oct 04 '22 14:10

Denys Séguret