Declare a constant array in Golang [SOLVED]


GOLANG Solutions, GO

Author: Tuan Nguyen
Reviewer: Deepak Prasad

In this tutorial, we will explore how to declare a constant array in Golang. First we have to understand what is constant and array golang:

constants: Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans. Because of the compile-time restriction, the expressions that define them must be constant expressions, evaluatable by the compiler. For instance, 1<<3 is a constant expression, while math.Sin(math.Pi/4) is not because the function call to math.Sin needs to happen at run time.

array: In computer science, an array is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key. An array is stored such that the position of each element can be computed from its index tuple by a mathematical formula. The simplest type of data structure is a linear array, also called one-dimensional array.

In Golang, an array isn't immutable by nature so you can't make it constant.

 

Access array from inner package

During runtime, slices and arrays are always evaluated:

package main

import "fmt"

func main() {
	ConstArray := []int{4, 7, 9}
	ConstArray2 := [3]int{174, 152, 36}
	ConstArray3 := [...]int{26, 27}

	fmt.Println(ConstArray)
	fmt.Println(ConstArray2)
	fmt.Println(ConstArray3)
}

Output:

[4 7 9]
[174 152 36]
[26 27]

[...] instructs the compiler to determine the array's own length. The use of [...] instead of [] ensures that you obtain a (fixed-size) array rather than a slice. As a result, the values are not fixed, but the size. Make the variables inaccessible to other packages by using a lower case first letter rather than constants:

For example here is the folder structure:

.
├── constantPackage
│   └── constant.go
└── main
    ├── constantArray.go
    └── gtk3.go

constant.go:

package constantPackage

var PublicConstArray = []int{4, 7, 9}
var privateConstArray = [3]int{174, 152, 36}

constantArray.go:

package main

import (
	"constantPackage"
	"fmt"
)

func main() {
        // can refer to this variable
	fmt.Println(constantPackage.PublicConstArray)
        // can not refer
	fmt.Println(constantPackage.privateConstArray)
}

Output:

# command-line-arguments
./constantArray.go:10:14: cannot refer to unexported name constantPackage.privateConstArray
./constantArray.go:10:14: undefined: constantPackage.privateConstArray

If we comment this line fmt.Println(constantPackage.privateConstArray) the output will be:

[4 7 9]

 

Using function to return constant array

A function that returns an array would be the closest thing we can do. By doing this, we can ensure that the components of the original array won't be changed (as it is "hard-coded" into the array). Here is an example of writing that function:

package main

import (
	"fmt"
)

func main() {
	arr1 := GetConstantArray()
	arr2 := GetConstantArray()

	fmt.Println(arr1)
	fmt.Println(arr2)
}

func GetConstantArray() []int {
	return []int{14, 15, 36, 125, 25}
}

Output:

[14 15 36 125 25]
[14 15 36 125 25]

 

Summary

Slice or const array are not supported in Go. It is thus because Go computes constant values at compilation time. Slices or arrays are always assessed in-place. Thus, the following software would produce a compilation error. But we can try some ways to create an array as shown above.

 

References

https://en.wikipedia.org/wiki/Array_(data_structure)
https://go.dev/blog/constants
https://go.dev/doc/effective_go#constants

 

Tuan Nguyen

Tuan Nguyen

He is proficient in Golang, Python, Java, MongoDB, Selenium, Spring Boot, Kubernetes, Scrapy, API development, Docker, Data Scraping, PrimeFaces, Linux, Data Structures, and Data Mining. With expertise spanning these technologies, he develops robust solutions and implements efficient data processing and management strategies across various projects and platforms. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment