I am new to the golang. Is it possible to mark a parameter as constant in function ? So that the parameter is not modified accidentally.
30
votes
Absence of constant parameter does not block what we want to achieve , but i feel its presence provide clear intention of that function. For example strlen(const char *str) in c tells that it doesn't modify the input string.
- Karthik G R
Chisnall in Go Programming Language Phrasebook recommends always passing by value in Go except when you explicitly need to modify the argument:Compiler is smart enough to know what to do. One of the reasons Go was invented was so that programmers would not have to worry about such details. I also tried to make analogies to C++ and Delphi when I first started playing with Go - now I no longer do so (the "GoTo" guys here have been very helpful with that)
- Vector
The go FAQ also recommends using references for passing around big structs, even if they are not modified, for memory optimization reasons. This is actually the case when the const parameters would come in handy.
- Ioanna
3 Answers
29
votes
No, this is currently not possible. There are several cases to distinguish:
- When passing a parameter "normally", i.e. by value, you don't have to worry about modifying it, since these parameters behave like local variables, so you can modify them inside the function, but your changes won't be visible outside the function. But, there is an exception to this rule...
- ...some Go types (e.g. pointers, slices, channels, maps) are reference types, which means changes to them will be visible outside of the function. Some details are given here.
- You can pass pointers (e.g., to structs) as parameters, in which case changes will be visible outside the function. If this is not intended, currently there is nothing you can do about it. So if you are passing pointers to avoid copying large structs, it is best to use this sparingly - remember, "Premature optimization is the root of all evil". Some hints are given in the Go FAQ here (it refers to method receivers, but it also applies to parameters).
7
votes
4
votes
There's still a handy application to the const parameter passed by value: you can't unintentionally change the initial value.
Consider following code:
func Generate(count int) (value []byte) {
value = make([]byte, count)
for i:=0; i<count; count++ {
value[i] = byte(i) // just for an example
}
return
}
This is a valid Go code, no warning or errors during the compilation. Such kind of typo might be painful to track.