1

How do I initialize a struct with a double pointer field? I am trying to initialize a struct as below:

type atype struct {
  val string
}

a := &struct {
    StringValue string
    Pointer **atype
}{
    StringValue: "FOO",
//this is the relevant bit
    Pointer : &(&atype{ 
      val: "test"
    })
}

This gives me an error : invalid pointer type **basicAppConfig for composite literal

What is wrong in my logic? I take the pointer to a pointer to the value.

I also tried to use

reflect.PtrTo(&atype{
    val: "string"
})

without success...

1
  • If you're ok with initializing only to first pointer, having the pointed-to pointer be nil, you can use new to your heart's content. play.golang.org/p/995hzR3EVWQ Commented Feb 15, 2018 at 23:31

1 Answer 1

8

Pointers are not addressable unless assigned to a variable. The ability to take the address of a composite literal without assigning it to a variable is limited to structs, arrays, slices, and maps.

To do what you want to do, you have to assign the pointer to a variable first, after which you can assign the address of that (pointer) variable within the struct literal:

https://play.golang.org/p/7WyS732H3cZ

package main

type atype struct {
    val string
}

func main() {
    at := &atype{
        val: "test",
    }

    a := &struct {
        StringValue string
        Pointer     **atype
    }{
        StringValue: "FOO",
        Pointer:     &at,
    }

    _ = a
}

References:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.