Golang: Assigning a value to struct member that is a pointer

17,883

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

Share:
17,883
Bart Silverstrim
Author by

Bart Silverstrim

Sysadmin, Assister for Users of Technology, Writer of Words, and Flixer of Nets

Updated on June 19, 2022

Comments

  • Bart Silverstrim
    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?

  • Bart Silverstrim
    Bart Silverstrim about 7 years
    My 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
    Zan Lynx about 7 years
    @BartSilverstrim Ah well I didn't test it. I guess I should have.
  • Zan Lynx
    Zan Lynx about 7 years
    @BartSilverstrim I fixed my first example.
  • nosequeldeebee
    nosequeldeebee almost 6 years
    This 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