Reputation: 1077
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.
Upvotes: 42
Views: 30446
Reputation: 31
A constant can be defined in the scope where the function has been defined.
const varName varType
func myFunction() {
...
}
Parameters of a function cannot be constant because it have to be a variable to be changeable inside the function. If a function parameter was constant, we needed to put its value in a variable to do operations on it.
Upvotes: 0
Reputation: 432
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.
Upvotes: 4
Reputation: 5258
No, this is currently not possible. There are several cases to distinguish:
Upvotes: 34
Reputation: 16440
No.
You can declare a constant inside a function body, but not as a parameter.
In Go, constants are created in compile time and can never change, while function parameters must change with each call at run time.
Upvotes: 8