Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constant Parameter in golang function

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.

like image 797
Karthik G R Avatar asked Feb 28 '14 09:02

Karthik G R


People also ask

How do you declare a constant variable in Golang?

To declare a constant and give it a name, the const keyword is used. Constants cannot be declared using the := syntax.

Can a parameter be a constant?

A parameter is a quantity that influences the output or behavior of a mathematical object but is viewed as being held constant. Parameters are closely related to variables, and the difference is sometimes just a matter of perspective.

What is const function parameter?

Declaring function parameters const indicates that the function promises not to change these values. In C, function arguments are passed by value rather than by reference. Although a function may change the values passed in, these changed values are discarded once the function returns.

Can constants be computed in Go?

In Go, constants provide complete safety in regards to the value they hold. They cannot be computed (making them used less often), but are guaranteed to always reference the same value.


1 Answers

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).
like image 61
rob74 Avatar answered Sep 17 '22 11:09

rob74