I'm trying to assign a value to a struct member that is a pointer, but it gives "panic: runtime error: invalid memory address or nil pointer dereference" at runtime...
package main
import (
"fmt"
"strconv"
)
// Test
type stctTest struct {
blTest *bool
}
func main() {
var strctTest stctTest
*strctTest.blTest = false
fmt.Println("Test is " + strconv.FormatBool(*strctTest.blTest))
}
The runtime error seems to come from the assignment of the value with *strctTest.blTest = false , but why? How do I set it to false?
Default values can be assigned to a struct by using a constructor function. Rather than creating a structure directly, we can use a constructor to assign custom default values to all or some of its members.
You can assign 0 into a pointer: ptr = 0; The null pointer is the only integer literal that may be assigned to a pointer.
Creating a Pointer using the built-in new() function You can also create a pointer using the built-in new() function. The new() function takes a type as an argument, allocates enough memory to accommodate a value of that type, and returns a pointer to it.
Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system. You can also use a pointer to a struct. A struct in Golang is a user-defined type which allows to group/combine items of possibly different types into a single type.
Why is it an error? Because a pointer only points. It doesn't create anything to point AT. You need to do that.
How to set it to false? This all depends on WHY you made it a pointer.
Is every copy of this supposed to point to the same bool? Then it should be allocated some space in a creation function.
func NewStruct() *strctTest {
bl := true
return &strctTest{
blTest: &bl,
}
}
Is the user supposed to point it at a boolean of his own? Then it should be set manually when creating the object.
func main() {
myBool := false
stctTest := strctTest{
blTest: &myBool
}
fmt.Println("Test is " + strconv.FormatBool(*strctTest.blTest))
}
Another way you can think of it is the zero value of a boolean is false.
This is not as clear but another way to do it.
https://play.golang.org/p/REbnJumcFi
I would recommend a New()
func that returns a reference to a initialized struct type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With