Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dereference a pointer in Go?

Tags:

pointers

go

In the Go language, is there any way to convert *string to string? (or, for that matter, any *T to T?)

I have looked on the internet and through some Go documentation, but I can't find it - may have missed it.

like image 525
acisola Avatar asked Apr 26 '14 22:04

acisola


People also ask

Can you dereference a function pointer?

As opposed to referencing a data value, a function pointer points to executable code within memory. Dereferencing the function pointer yields the referenced function, which can be invoked and passed arguments just as in a normal function call.

Does Go automatically dereference?

Go performs automatic dereferencing for struct data type in its specification. Hence, you do not need to de-reference it explicitly. Quote: As with selectors, a reference to a non-interface method with a value receiver using a pointer will automatically dereference that pointer: pt.Mv is equivalent to (*pt).

How do you dereference a pointer to a pointer?

x is a pointer to a pointer to int. *x yields a int* (pointer to int ) **x = is like *(*x) = so you first obtain the pointer to int then by dereferencing you are able to set the value at the address.

Can you use pointers in Go?

In Go a pointer is represented using the * (asterisk) character followed by the type of the stored value. In the zero function xPtr is a pointer to an int . * is also used to “dereference” pointer variables. Dereferencing a pointer gives us access to the value the pointer points to.


1 Answers

To turn a *T into a T, use the * operator:

func Dereference(strptr *string) string {
    return *strptr
}

I highly suggest you to read about pointers before proceeding with the language. They are a fundamental concept without which it is impossible to use the language efficiently.

like image 164
fuz Avatar answered Oct 14 '22 13:10

fuz