tags:

views:

482

answers:

3

I know that pointers in Go allow mutation of a function's arguments, but wouldn't it have been simpler if they adopted just references (with appropriate const or mutable qualifiers). Now we have pointers and for some built-in types like maps and channels implicit pass by reference.

Am I missing something or are pointers in Go just an unnecessary complication?

+7  A: 

References cannot be reassigned, while pointers can. This alone makes pointers useful in many situations where references could not be used.

zildjohn01
+3  A: 

Go is designed to be a terse, minimalist language. It therefore started with just values and pointers. Later, by necessity, some reference types (slices, maps, and channels) were added.


The Go Programming Language : Language Design FAQ : Why are maps, slices, and channels references while arrays are values?

"There's a lot of history on that topic. Early on, maps and channels were syntactically pointers and it was impossible to declare or use a non-pointer instance. Also, we struggled with how arrays should work. Eventually we decided that the strict separation of pointers and values made the language harder to use. Introducing reference types, including slices to handle the reference form of arrays, resolved these issues. Reference types add some regrettable complexity to the language but they have a large effect on usability: Go became a more productive, comfortable language when they were introduced."

link text


Fast compilation is a major design goal of the Go programming language; that has its costs. One of the casualties appears to be the ability to mark variables (except for basic compile time constants) and parameters as immutable. It's been requested, but turned down.


golang-nuts : go language. Some feedback and doubts.

"Adding const to the type system forces it to appear everywhere, and forces one to remove it everywhere if something changes. While there may be some benefit to marking objects immutable in some way, we don't think a const type qualifier is to way to go."

link text

peterSO
A: 

"References cannot be reassigned, while pointers can. [...]" zildjohn01

Why not? Java example:

    String s = "foo";
    s = "bar";
45g
String s = "foo"; String p = s; s = "bar"; // p is still foo.
Nick Johnson
Right, and you want to be able to do this instead? char* v = "foo"; char** s = char** p = s; *s = "bar"; // *p == "bar"This is easy to simulate with references if your reference refers to a mutable thing, e.g. in Java:AtomicReference<String> ref1 = new AtomicReference<String>("foo");AtomicReference<String> ref2 = ref1;ref1.set("bar");assert "bar".equals(ref2.get());So I still fail to see what pointers would offer you in Go.
45g
references in go are not the same as references in Java. Java references are more like C++ pointers without the pointer arithmetics.
hasen j