go - 从结构内部的指向 float32 的指针获取值?

标签 go

我正在从数据库中提取一些数据 - 我有一个指向 float32 的指针 - 因为如果我使用指针 - 那么我能够检查它是否为 nil(通常可能是 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...
    */
}

最佳答案

The Go Programming Language Specification

Address operators

For an operand x of pointer type *T, the pointer indirection *x denotes the variable of type T pointed to by x. If x is nil, an attempt to evaluate *x will cause a run-time panic.


使用 * 运算符。例如,

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

Playground :https://play.golang.org/p/8URumKoVl_t

输出:

3.14159

由于您是 Go 新手,请使用 A Tour of Go .游览解释了很多事情,包括指示。

Pointers

Go has pointers. A pointer holds the memory address of a value.

The type *T is a pointer to a T value. Its zero value is nil.

var p *int

The & operator generates a pointer to its operand.

i := 42
p = &i

The * operator denotes the pointer's underlying value.

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

This is known as "dereferencing" or "indirecting".

Unlike C, Go has no pointer arithmetic.

关于go - 从结构内部的指向 float32 的指针获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50539159/

相关文章:

go 项目构建失败 : lfstackPack redeclared in this block

go - 如何在 cgo 中正确使用 64 位 TDM-GCC?

go - 无法使用 protobuf 解码字节

file - 如何将结构作为二进制数据写入 golang 中的文件?

python - Go 真的能比 Python 快那么多吗?

go - 如何从 PUT、DELETE 方法 golang (gin gonic) 中检索数据

mongodb - 在 Mongo-go-driver 中创建一个独特的字段

docker - 如何在 Docker 容器中自动重启 golang 应用程序?

go - 在 golang 中将变量传递给测试用例的惯用方法

Golang 类型切换需要(冗余)类型断言