Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 948
Bart Silverstrim Avatar asked May 05 '17 18:05

Bart Silverstrim


People also ask

How do you assign a value to a struct in Golang?

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.

Can a pointer be assigned a value?

You can assign 0 into a pointer: ptr = 0; The null pointer is the only integer literal that may be assigned to a pointer.

How do I assign a pointer in Golang?

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.

Are structs pointers in Golang?

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.


2 Answers

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))

}
like image 113
Zan Lynx Avatar answered Sep 23 '22 12:09

Zan Lynx


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.

like image 30
JT. Avatar answered Sep 24 '22 12:09

JT.