gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:31:37 25 4
gpt4 key购买 nike

我正在从数据库中提取一些数据 - 我有一个指向 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com