I am pulling in some data from a db - and I have a pointer to a float32 - because if I use a pointer - then I am able to check if it is nil (which it quite often might be).
When it is not nil, I want to get the value - how do I dereference it so I can get the actual float32? I can't actually find a link for that anywhere! I know exactly what I want to do, and I just can't find the syntax in Go, which I am still very new to - all help appreciated.
I know how to dereference the pointer if it is a straight float32...
but if I have the following struct...
type MyAwesomeType struct{
Value *float32
}
Then after I do :
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.
Use the *
operator. For example,
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
Output:
3.14159
Since you are new to Go, take A Tour of Go . The tour explains many things, including pointers.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.