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