Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Const struct in Go (Golang)

Posted on September 30, 2023September 30, 2023 by admin

Table of Contents

  • Overview
  • Example

Overview

Go only supports four types of constant

  • Numeric ( int, int64, float, float64, complex128 etc)
  • String
  • Character or rune
  • Boolean

It doesn’t support const struct. So below program would raise a compilation error

Example

package main
import "fmt"
type employee struct {
name string
age int
}
func main() {
const e = employee{
name: "John",
age: 21,
}
fmt.Println(e)
}

Output

const initializer employee literal is not a constant

However workaround is to have a function which could return a struct. In a way that fulfills the purpose of a constant struct as it would return the same struct everytime

package main
import "fmt"
type employee struct {
name string
age int
}
func main() {
e := baseEmployee()
fmt.Println(e)
}
func baseEmployee() employee {
return employee{
name: "Unnamed",
age: 0,
}
}

Output

{Unnamed 0}
  • go
  • golang
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP