指向Golang中的Struct

时间:2012-10-17 09:51:46

标签: pointers go

我在实现以下代码时遇到错误:

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

这给了我一个关于“ptr.a的无效间接(类型int)......”的错误。还有为什么编译器不给我关于ptrInt的错误?提前谢谢。

1 个答案:

答案 0 :(得分:13)

只做

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

您实际上是在++上尝试应用*(ptr.a)ptr.a是一个int,而不是指向int的指针。

您可以使用(*ptr).a++但不需要这样做,因为如果ptr.a是指针,Go会自动解决ptr,这就是Go中没有->的原因

相关问题