在Golang中指向结构体的指针

8

在实现以下代码时,我遇到了一个错误:

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个回答

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++,但这并不是必需的,因为Go会自动解决 ptr.a 问题,前提是 ptr 是一个指针。这就是为什么在 Go 中不需要使用 -> 符号。


1
谢谢你的回答,对我很有帮助。 - Coder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接