convert string to *string

32,542 views
Skip to first unread message

cerovi...@gmail.com

unread,
Oct 7, 2015, 5:54:48 AM10/7/15
to golang-nuts
Hi,

newbie here, I have to do something like this (dont ask me why :-):

var a *string
var b string
b = "test"
a = b

error: cannot use b (type string) as type *string in assignment

I tried:

a = *string(b)

error: invalid indirect of string(b) (type string)


Help

Jan Mercl

unread,
Oct 7, 2015, 6:00:26 AM10/7/15
to golang-nuts
On Wed, Oct 7, 2015 at 11:54 AM <cerovi...@gmail.com> wrote:

> I tried:
>
> a = *string(b)
>
> error: invalid indirect of string(b) (type string)

a = &b

--

-j

Staven

unread,
Oct 7, 2015, 6:03:37 AM10/7/15
to golang-nuts
On Wed, Oct 07, 2015 at 02:54:34AM -0700, cerovi...@gmail.com wrote:
> Hi,
>
> newbie here, I have to do something like this (dont ask me why :-):
I'm willing to bet dollars that no, in fact, you don't have to do this.

>
> var a *string
> var b string
> b = "test"
> a = b

a = &b

Read the spec.
Seriously. You may have bad experiences with specifications. It might look scary.
It's not scary.

cerovi...@gmail.com

unread,
Oct 7, 2015, 6:11:45 AM10/7/15
to golang-nuts
:) was googling with no luck, thnx

cerovi...@gmail.com

unread,
Oct 7, 2015, 6:25:57 AM10/7/15
to golang-nuts, sta...@staven.pl
I have a struct that have field with type *string (because that correlates with nullable field in database)
I receive string from web service that I need to put in this field

Please clarify

Caleb Doxsey

unread,
Oct 7, 2015, 6:39:23 AM10/7/15
to golang-nuts, cerovi...@gmail.com
With pointers you have two options:
  1. The previously mentioned a = &b, which sets a to the address of b.
  2. You can also do *a = b, which follows the pointer and stores the value of b inside it.
If you have a struct:

type MyStruct {
    X *string
}

#1 would look like:

var s = MyStruct{X: &b}

and #2 would look like:

var s = MyStruct{X: new(string)}
*s = b

(Notice that you have to use new, since you can't dereference a nil pointer) 

As for which one to use, it depends on what you're doing. This might be helpful: golang-book.com/books/intro/8.

cerovi...@gmail.com

unread,
Oct 7, 2015, 6:47:03 AM10/7/15
to golang-nuts, cerovi...@gmail.com
thnx, I'll take a look

Staven

unread,
Oct 7, 2015, 6:52:08 AM10/7/15
to golang-nuts
On Wed, Oct 07, 2015 at 03:25:41AM -0700, cerovi...@gmail.com wrote:
> I have a struct that have field with type *string (because that correlates
> with nullable field in database)

https://golang.org/pkg/database/sql/#NullString

Strings in go are immutable, so a string value is kinda-sorta already like a pointer.
There are legitimate cases where a pointer to string makes sense (see e.g. the flag package),
but usually it's just people who don't know any better.
Newbies are, logically, most often people who don't know any better.

Reply all
Reply to author
Forward
0 new messages