Loading
svg
Open

Golang's const array

January 21, 20243 min read

Constant changes are very common in the development world. Like most programming languages, Go allows us to declare variables as constant values. This prevents modification of prices after declaration.

In this guide, we will learn how to define constant arrays in the Go programming language. It allows you to store a collection of values ​​that cannot be changed in a single entity.

What is a static array?

As the name suggests, a static array is an array whose elements are predefined as constants during compile time.

Therefore, once we declare an array as static, we cannot change its elements during runtime which provides immutability, compile-time safety and performance benefits (in some cases).

Declare a const array in Golang

Unfortunately, we cannot directly declare an array as constant because arrays are mutable data structures. Since we can only set the constants property to immutable values, this means we have to implement a custom feature to work with constants arrays.

The most efficient technique to define a static array in Go is to use […] Syntax. This allows the compiler to estimate the length of the array based on the number of elements during initialization.

package main
Import ,

“fmt”
,

var address , []string,
“localhost:3306”,
“localhost:4453”,
“development.remote:6379”,
,
main work,, ,
FMT.println,“Days of week:”,
For ,, Address:, Category addresses ,
FMT.println,Fifth note of musical scale,
,
,

In this case, we are using […] Expression to let the compiler estimate the size of an array based on the number of elements.

Note: It is good to understand that this does not mean that the array is a constant. However, it shows read-only properties which prevents modification. However, it is up to you to ensure that the array is read-only within your code.

array of integers

If you need to create a constant-like array of integers, we can use the “iota” keyword. This allows us to declare a sequence of increasing integers within a constant declaration.

An example usage is as follows:

package main
Import ,

“fmt”
,

const ,

Zero , 10 + quota
One
Two
Three
,

main work,, ,
Constant:, [4]int here,Zero, One, Two, Three,
FMT.println,constArray,
,

It basically creates a series of constant integers and treats them as an array.

conclusion

In this tutorial, we learned how we can implement an array like a constant in Go by setting read-only properties on the array. Keep in mind that you cannot declare an array as constant because it is a mutable data structure.

How do you vote?

0 People voted this article. 0 Upvotes - 0 Downvotes.
svg

What do you think?

Show comments / Leave a comment

Leave a reply

Loading
svg