How to create a Struct Instance Using a Struct Literal in Golang?


In Golang, we can create a struct instance using a struct literal, which is a convenient and concise way to initialize a new struct.

A struct is a composite data type that groups together zero or more named values of arbitrary types. It is defined using the type keyword followed by the name of the struct and its fields.

Syntax

Here's an example struct −

type Person struct {
   Name string
   Age  int
}

To create a new instance of this struct using a struct literal, we can simply specify the field names and values within curly braces −

p := Person{Name: "John", Age: 30}

This creates a new instance of the Person struct with the Name field set to "John" and the Age field set to 30.

We can also omit the field names if we provide the values in the same order as the struct fields −

p := Person{"John", 30}

This creates a new instance of the Person struct with the Name field set to "John" and the Age field set to 30, in the same order as they appear in the struct definition.

Struct literals can be useful when creating test data or initializing struct fields with default values. For example, let's say we have a struct representing a product −

type Product struct {
   Name     string
   Price    float64
   Quantity int
}

We can create a default instance of this struct using a struct literal with default values −

defaultProduct := Product{Name: "Untitled Product", Price: 0.0, Quantity: 1}

This creates a new instance of the Product struct with the Name field set to "Untitled Product", the Price field set to 0.0, and the Quantity field set to 1.

Example

package main

import "fmt"

type Person struct {
   firstName string
   lastName  string
   age       int
}

func main() {
   // Creating struct instance using a struct literal
   person := Person{
      firstName: "John",
      lastName:  "Doe",
      age:       25,
   }

   fmt.Printf("First Name: %s\n", person.firstName)
   fmt.Printf("Last Name: %s\n", person.lastName)
   fmt.Printf("Age: %d\n", person.age)
}

Output

First Name: John
Last Name: Doe
Age: 25

Conclusion

struct literal is a concise way to create a new struct instance with the desired field values. It can be used to initialize struct fields with default values, or to create test data.

Updated on: 05-May-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements