pointers - 在 Go 中使用指针的困惑

标签 pointers go struct

我有如下示例代码。

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

问题是,为什么我必须在 num 变量前加上星号 (*) 而不是 a.Color? 如果我对 a.Color 这样做,它说

invalid indirect of a.Color (type string)

或者如果我从 num 中删除一个星号 (*),它会显示

invalid operation: num + 2 (mismatched types *int and int)

这让我很困惑,谁能解释一下为什么?

最佳答案

这是两种不同的情况:

案例1

num 是一个指向 int 的指针,因此您需要将整数值添加到存储在 num 指向的地址的值中。因此,您取消引用 num 指针以获取存储在其中的值:

func TestTest(num *int) {
    *num = *num + 2 // dereference the pointer to get the value.
}

案例2

您正在为 Apple 结构的 Color 字段分配一个字符串值,这不是一个指针。但是您使用的是指向结构而不是字段的指针。这就是为什么您能够像这样分配一个值:

func Eat(a *Apple) { // a is the pointer to struct.
    a.Color = "green"
}

现在,如果您想生成与第一种情况相同的错误,请在结构中创建一个指针类型的 Color 字段,如下所示:

type Apple struct {
    Color *string // this is the pointer value which will throw the same error in your current implementation.
}

Go playground 上的错误代码在使用 struct 时尝试将指针类型值分配给非指针变量时。

解决方案

要在结构中使用指针字段的情况下设置值,请使用反射:

package main

import (
    "fmt"
    "reflect"
)

//I have my sample code like this.

type Apple struct {
    Color *string
}

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

func TestTest(num *int) {
    *num = *num + 2
}
func Eat(a *Apple) {
    str := "green"
    r := reflect.ValueOf(a)
    elm := r.Elem().FieldByName("Color")
    elm.Set(reflect.ValueOf(&str))
    fmt.Printf("%+v", (*a).Color)
}

Playground示例

还有一件事要注意,反射的值实际上是 reflect.Ptr 所以我们可以做的是我们可以遍历结构字段来获取值,然后使用 reflect。间接获取指针类型颜色字段的值。

func Eat(a *Apple) {
    str := "green"
    r := reflect.ValueOf(a).Elem()
    elm := r.FieldByName("Color")
    elm.Set(reflect.ValueOf(&str))
    fmt.Printf("%+v\n", (*a).Color)
    for i := 0; i < r.NumField(); i++ {
        valueField := r.Field(i)
        fmt.Println(reflect.Indirect(valueField))
    }
    // or use FieldByName to get the value of a field.
    st := "Color"
    fmt.Println(reflect.Indirect(reflect.ValueOf(a).Elem().FieldByName(st)))
}

关于pointers - 在 Go 中使用指针的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52638929/

相关文章:

go - 从 goroutine 中捕获返回值

c++ - 在 C 和 C++ 中创建点数组

go - 如何从 map 界面解析特定键?

c - 为什么通过引用传递时 C 中结构的大小会增加

objective-c - Objective C 结构和内存管理

c - 我如何知道当前持有的是哪种类型(int、double、float 等)?

c - 将 C 字符数组拆分为单词

c++ - 从指针 vector 中删除对象

c# - 值类型和引用类型的基本区别

调试 go 应用程序不会在断点处停止