小编Pat*_*dee的帖子

混淆在Go中使用指针

我有下面的示例代码。

type Apple struct {
    Color string
}
//In this way, the code runs just fine.
func main(){
        var test = 6
        TestTest(&test)
        fmt.Println(test)
        a := Apple{"red"}
        Eat(&a)
        fmt.Println(a.Color)
}


    func TestTest(num *int) {
        *num = *num + 2
    }
    func Eat(a *Apple) {
        a.Color = "green"
    }
Run Code Online (Sandbox Code Playgroud)

问题是,为什么我必须在num变量之前放一个star(*)而不是a.Color?如果我这样做a.Color,它说

无效的a.Color间接值(类型字符串)

或者如果我从中删除了星号(*)num,它会说

无效的运算:num + 2(类型不匹配的* int和int)

这让我感到困惑,有人可以解释为什么吗?

struct pointers go

1
推荐指数
2
解决办法
376
查看次数

标签 统计

go ×1

pointers ×1

struct ×1