# Using golang constants in struct [SOLVED]

Author: Tuan Nguyen

In today's post, we will discuss how to declare a constant in a Golang struct. For example:

`Constants`: There are boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants. Rune, integer, floating-point, and complex constants are collectively called numeric constants.

A constant value is represented by a rune, integer, floating-point, imaginary, or string literal, an identifier denoting a constant, a constant expression, a conversion with a result that is a constant, or the result value of some built-in functions such as unsafe.Sizeof applied to certain values, cap or len applied to some expressions, real and imag applied to a complex constant and complex applied to numeric constants. The boolean truth values are represented by the predeclared constants true and false. The predeclared identifier iota denotes an integer constant.

## Constants struct in Go

Go only supports four types of constants as above listed. It doesnโt support constant struct. So below example would raise an error:

``````package main

import "fmt"

type Person struct {
name string
age  int
}

func main() {
const per = Person{
name: "Harry Potter",
age:  100000,
}
fmt.Println(per)
}``````

Output:

```# command-line-arguments
.\structConst.go:11:14: Person{โฆ} (value of type Person) is not constant```

A solution is to have a function that returns a struct. In a way, that fulfills the purpose of a constant struct because it always returns the same struct:

``````package main

import "fmt"

type Person struct {
name string
age  int
}

func main() {
per := constantPerson()
fmt.Println(per)

per2 := constantPerson()
fmt.Println(per2 == per)
}

func constantPerson() Person {
return Person{
name: "Harry Potter",
age:  100000,
}
}
``````

Output:

```{Harry Potter 100000}
true```

## Declare golang constants in struct

For example, we want to declare constant in a struct. Letโs assume that `constants.CONSTANT_STRING` has the value "Hello world". Then this syntax:

``````type Person struct {
name string
age  int
constants.CONSTANT_STRING string
}``````

would evaluate to:

``````type Person2 struct {
name string
age  int
"Hello world" string
}``````

which is incorrect syntax and has no semantic meaning. So in Golang, we can not directly declare a constant in a struct. If you want to assign a greeting (a constant string) to each `Person` variable, you can add an unexported field to the struct along with a method that returns greetingย the value. This way, code outside the package can read the constant string through the method but cannot directly access the variable:

``````package main

import (
"fmt"
)

const (
GREETING1 = "Hello World!"
GREETING2 = "Bonjour!"
)

type Person struct {
name     string
age      int
greeting string
}

func (per Person) getGreeting() string {
return per.greeting
}

func main() {
person1 := Person{
name:     "Anna",
age:      21,
greeting: GREETING1,
}
fmt.Println("Greeting:", person1.getGreeting())
}``````

Output:

`Greeting: Hello World!`

## Summary

In today's post, I have given examples of declaring a constant struct or constants in a struct. In general, golang does not allow declaring a constant struct and constant within a struct. But we can use a custom function to perform this purpose. To understand more about using constant in golang, read the declare constant maps article.

## References

https://go.dev/ref/spec#Constants

Views: 206

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.

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

We try to offer easy-to-follow guides and tips on various topics such as Linux, Cloud Computing, Programming Languages, Ethical Hacking and much more.