Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the asterisk do in "Go"?

Tags:

go

I'm a web developer looking to expand my horizons in order to get better at programming as a whole. I've done a bit Java and some simple Android applications. I'm now looking into lower level languages like C and Go (which I must say has some beautiful syntax and great ideas thus far, though I'm maybe too inexperienced to comment).

So yeah I've been going through and trying to understand the examples on the Go website and I keep coming across a special asterisk character in examples like this:

s := "hello" if s[1] != 'e' {     os.Exit(1) } s = "good bye" var p *string = &s *p = "ciao" 

Also, I just noticed, what's with the &s? Is it assignment by reference (I might be using PHP talk here)?

like image 894
rich97 Avatar asked Aug 24 '10 00:08

rich97


People also ask

What is Asterisk used for in golang?

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.

What does * and & indicate in golang?

1. simply saying & will point to variable that has no value while * will point to variable that has value in there.

What is the star in Go?

Star Pieces increase the amount of Stardust you earn by 50% for a limited period of time. Star Pieces typically last for 30 minutes but may last longer during special events.

What does * Struct mean in golang?

A struct (short for "structure") is a collection of data fields with declared data types. Golang has the ability to declare and create own data types by combining one or more types, including both built-in and user-defined types.


1 Answers

* attached to a type (*string) indicates a pointer to the type.

* attached to a variable in an assignment (*v = ...) indicates an indirect assignment. That is, change the value pointed at by the variable.

* attached to a variable or expression (*v) indicates a pointer dereference. That is, take the value the variable is pointing at.

& attached to a variable or expression (&v) indicates a reference. That is, create a pointer to the value of the variable or to the field.

like image 109
Markus Jarderot Avatar answered Oct 08 '22 22:10

Markus Jarderot