首页 > 解决方案 > 从结构内部的指向 float32 的指针中获取值?

问题描述

我正在从 db 中提取一些数据——我有一个指向 float32 的指针——因为如果我使用指针——那么我可以检查它是否为 nil(通常可能是)。

当它不是 nil 时,我想获取该值 - 如何取消引用它以便获取实际的 float32?我实际上无法在任何地方找到该链接!我确切地知道我想做什么,但我只是在 Go 中找不到语法,我还是很陌生 - 所有帮助表示赞赏。

如果它是一个直接的 float32,我知道如何取消引用指针......

但如果我有以下结构......

type MyAwesomeType struct{
    Value *float32
}

然后在我这样做之后:

if myAwesomeType.Value == nil{
    // Handle the error later, I don't care about this yet...
} else{
    /* What do I do here? Normally if it were a straight float32
     * pointer, you might just do &ptr or whatever, but I am so
     * confused about how to get this out of my struct...
    */
}

标签: go

解决方案


Go 编程语言规范

地址运算符

对于指针类型 *T 的操作数 x,指针间接 *x 表示 x 指向的类型 T 的变量。如果 x 为 nil,则尝试评估 *x 将导致运行时恐慌。


使用*运算符。例如,

package main

import "fmt"

type MyAwesomeType struct {
    Value *float32
}

func main() {
    pi := float32(3.14159)
    myAwesomeType := MyAwesomeType{Value: &pi}

    if myAwesomeType.Value == nil {
        // Handle the error
    } else {
        value := *myAwesomeType.Value
        fmt.Println(value)
    }
}

游乐场: https: //play.golang.org/p/8URumKoVl_t

输出:

3.14159

由于您是 Go 新手,请参加A Tour of Go。这次旅行解释了很多事情,包括指针。

指针

Go 有指针。指针保存一个值的内存地址。

类型*T是指向T值的指针。它的零值为nil

var p *int

&运算符生成指向其操作数的指针。

i := 42
p = &i

*运算符表示指针的基础值。

fmt.Println(*p) // read i through the pointer p
*p = 21         // set i through the pointer p

这被称为“取消引用”或“间接”。

与 C 不同,Go 没有指针算法。


推荐阅读