Assign to String Pointer

13,096 views
Skip to first unread message

Luke Mauldin

unread,
Mar 27, 2012, 8:03:32 PM3/27/12
to golan...@googlegroups.com
If I have a struct as shown below that contains a string pointer, how do I assign or initialize the string pointer?

type foo struct {
strPtr *string
strVal string
}
_ = foo {strVal: "a"} //This works
_ = foo {strPtr: "b"} //This gives me the error: cannot use "b" (type string) as type *string in field value

I am having to use a string pointer type because my struct is being unmarshalled using encoding/json and if the incoming string is null, JSON requires a string pointer to correctly unmarshall the value.  I think that JSON is using reflection to populate the string pointer but I want to be able to set and manipulate the string pointer from regular Go code without using reflection.  Is this possible and if so, how?

Luke

David Symonds

unread,
Mar 27, 2012, 8:06:05 PM3/27/12
to Luke Mauldin, golan...@googlegroups.com
Use a helper function or variable:

s := "b"
_ = foo{strPtr: &s}

or

func sPtr(s string) *string { return &s }
_ = foo{strPtr: sPtr("b")}


Dave.

Evan Shaw

unread,
Mar 27, 2012, 8:05:49 PM3/27/12
to Luke Mauldin, golan...@googlegroups.com
On Wed, Mar 28, 2012 at 1:03 PM, Luke Mauldin <lukem...@gmail.com> wrote:
> If I have a struct as shown below that contains a string pointer, how do I
> assign or initialize the string pointer?

There's no way to do it in a single expression. You need to do something like:

str := "a"
_ = foo{strPtr: &str}

- Evan

Luke Mauldin

unread,
Mar 27, 2012, 8:14:05 PM3/27/12
to golan...@googlegroups.com, Luke Mauldin
Thank you both, your solutions work perfectly.

On Tuesday, March 27, 2012 7:05:49 PM UTC-5, Evan Shaw wrote:
Reply all
Reply to author
Forward
0 new messages