Go Struct

A struct, short for “structure,” is a way to bundle together multiple pieces of data with different types into a single entity. Unlike arrays, which store multiple values of the same type, structs allow different types to coexist within a single unit, making them useful for organizing related data.

Tutorials dojo strip



Declaring a Struct

In Go, a struct is defined using the type keyword followed by the struct name and its members.

Syntax:

Go


Example:

Here, Motorcycle is a struct that groups multiple details about a motorcycle, such as brand, model, year, and price.

Go

Each member of the struct can have a different data type. In this example, brand and model are strings, while year and price are integers.




Accessing Struct Members

To access the elements within a struct, use the dot (.) operator.

Example:

Below, two instances of the Motorcycle struct (bike1 and bike2) are created and their attributes are assigned values.

Go

Output:

Go




Passing a Struct as a Function Argument

Structs can also be passed as arguments to functions, allowing for cleaner code when working with structured data.

Example:

The following program defines a function printMotorcycle() that takes a Motorcycle struct as an argument and prints its details.

Go

Output:

Go

Tutorials dojo strip