简体   繁体   中英

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

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?

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.

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

Following up on JTs Answer, I also would recommend using the new function as such:

package main

import (
    "fmt"
    "strconv"
)

// Test
type stctTest struct {
    blTest *bool
}

func main() {

    strctTest := &stctTest{
        blTest: new(bool),
    }

    *strctTest.blTest = true

    fmt.Println("Test is " + strconv.FormatBool(*strctTest.blTest))
}

After initializing the memory with new() , you can directly assign a value to the de-referenced pointer. This way you do not need to use another variable to get the address from.

https://go.dev/play/p/BmekoTalQVh

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM