Golang: Assigning a value to struct member that is a pointer
Solution 1
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))
}
Solution 2
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.
Solution 3
You could also do something like:
package main
import (
"fmt"
"strconv"
)
// Test
type stctTest struct {
blTest *bool
}
func main() {
strctTest := stctTest{
blTest: &[]bool{true}[0],
}
fmt.Println("Test is " + strconv.FormatBool(*strctTest.blTest))
}
https://play.golang.org/p/OWSosQhrUql
Bart Silverstrim
Sysadmin, Assister for Users of Technology, Writer of Words, and Flixer of Nets
Updated on June 19, 2022Comments
-
Bart Silverstrim almost 2 years
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?
-
fhe about 7 yearsHere is a nice explanation of pointers in Go: dave.cheney.net/2017/04/26/…
-
-
Bart Silverstrim about 7 yearsMy attempt to try the first method gave a compiler error ("invalid pointer type *bool for composite literal") but the second method worked for my purposes. Thank you!
-
Zan Lynx about 7 years@BartSilverstrim Ah well I didn't test it. I guess I should have.
-
Zan Lynx about 7 years@BartSilverstrim I fixed my first example.
-
nosequeldeebee almost 6 yearsThis didn't really answer the OP's question. He asked how to assign a value to a bool, not how to make a new memory allocation. In your example you should add how to assign a value to it. See play.golang.org/p/iqOD5hLcPPp