Golang Structs Tutorial with Examples

Golang Structs Tutorial with Examples

A struct is a user-defined type that contains a collection of named fields/properties. It is used to group related data together to form a single unit. Any real-world entity that has a set of properties can be represented using a struct.

If you’re coming from an object-oriented background, you can think of a struct as a lightweight class that supports composition but not inheritance.

Defining a struct type

You can define a new struct type like this -

The type keyword introduces a new type. It is followed by the name of the type ( Person ) and the keyword struct to indicate that we’re defining a struct . The struct contains a list of fields inside the curly braces. Each field has a name and a type.

Note that, you can collapse fields of the same type like this:

Declaring and Initializing a struct

Declaring a variable of a struct type.

Just like other data types, you can declare a variable of a struct type like this -

The above code creates a variable of type Person that is by default set to zero. For a struct, zero means all the fields are set to their corresponding zero value . So the fields FirstName and LastName are set to "" , and Age is set to 0 .

Initializing a struct

You can initialize a variable of a struct type using a struct literal like so -

Note that you need to pass the field values in the same order in which they are declared in the struct . Also, you can’t initialize only a subset of fields with the above syntax -

Naming fields while initializing a struct

Go also supports the name: value syntax for initializing a struct (the order of fields is irrelevant when using this syntax).

You can separate multiple fields by a new line for better readability (the trailing comma is mandatory in this case) -

The name: value syntax allows you to initialize only a subset of fields. All the uninitialized fields are set to their corresponding zero value -

Complete Example: Defining and Initializing struct types

Accessing fields of a struct.

You can access individual fields of a struct using the dot ( . ) operator -

Pointer to a struct

You can get a pointer to a struct using the & operator -

As demonstrated in the above example, Go lets you directly access the fields of a struct through the pointer without explicit dereference.

Creating a struct and obtaining a pointer to it using the built-in new() function

You can also use the built-in new() function to create an instance of a struct . The new() function allocates enough memory to fit all the struct fields, sets each of them to their zero value and returns a pointer to the newly allocated struct -

Exported vs Unexported Structs and Struct Fields

Any struct type that starts with a capital letter is exported and accessible from outside packages. Similarly, any struct field that starts with a capital letter is exported.

On the contrary, all the names starting with a small letter are visible only inside the same package.

Let’s see an example. Consider the following package hierarchy of our Go program -

customer.go

And, here is the driver program main.go -

As you can see, the names address and married are unexported and not accessible from the main package.

Structs are value types

Structs are value types. When you assign one struct variable to another, a new copy of the struct is created and assigned. Similarly, when you pass a struct to another function, the function gets its own copy of the struct .

Struct Equality

Two struct variables are equal if all their corresponding fields are equal -

In this article, you learned the basics of structs. But there is a lot more to explore about structs like methods on a struct, struct composition, embedded fields, promoted fields etc. I will cover these topics in future articles.

Next Article: Golang Methods Tutorial with Examples
Code Samples: github.com/callicoder/golang-tutorials
  • Structs in Go

Share on social media

Create, initialize and compare structs

struct assignment golang

Struct types

2 ways to create and initialize a new struct, compare structs.

A struct is a typed collection of fields, useful for grouping data into records.

  • To define a new struct type , you list the names and types of each field.
  • The default zero value of a struct has all its fields zeroed.
  • You can access individual fields with dot notation .

The new keyword can be used to create a new struct. It returns a pointer to the newly created struct.

You can also create and initialize a struct with a struct literal .

  • An element list that contains keys does not need to have an element for each struct field. Omitted fields get the zero value for that field.
  • An element list that does not contain any keys must list an element for each struct field in the order in which the fields are declared.
  • A literal may omit the element list; such a literal evaluates to the zero value for its type.

For further details, see The Go Language Specification: Composite literals .

You can compare struct values with the comparison operators == and  != . Two values are equal if their corresponding fields are equal.

Go step by step

struct assignment golang

Core Go concepts: interfaces , structs , slices , maps , for loops , switch statements , packages .

Golang Programs

Golang Tutorial

Golang reference, beego framework, golang struct.

Learn to create user-defined types by combining with other types.

Introduction

A struct (short for "structure") is a collection of data fields with declared data types. Golang has the ability to declare and create own data types by combining one or more types, including both built-in and user-defined types. Each data field in a struct is declared with a known type, which could be a built-in type or another user-defined type.

Structs are the only way to create concrete user-defined types in Golang. Struct types are declared by composing a fixed set of unique fields. Structs can improve modularity and allow to create and pass complex data structures around the system. You can also consider Structs as a template for creating a data record, like an employee record or an e-commerce product.

The declaration starts with the keyword type , then a name for the new struct, and finally the keyword struct . Within the curly brackets, a series of data fields are specified with a name and a type.

Declaration of a Struct Type

A struct type rectangle is declared that has three data fields of different data-types. Here, struct used without instantiate a new instance of that type.

The rectangle struct and its fields are not exported to other packages because identifiers are started with an lowercase letter. In Golang, identifiers are exported to other packages if the name starts with an uppercase letter, otherwise the accessibility will be limited within the package only.

Creating Instances of Struct Types

The var keyword initializes a variable rect . Using dot notation, values are assigned to the struct fields.

The struct is printed to the terminal, showing the values have been assigned.

Creating a Struct Instance Using a Struct Literal

Creates an instance of rectangle struct by using a struct literal and assigning values to the fields of the struct.

Struct Instantiation Using new Keyword

An instance of a struct can also be created with the new keyword. It is then possible to assign data values to the data fields using dot notation.

Two instances of the rectangle struct are instantiated, rect1 points to the address of the instantiated struct and rect2 is the name of a struct it represents.

Struct Instantiation Using Pointer Address Operator

Creates an instance of rectangle struct by using a pointer address operator is denoted by & symbol.

Nested Struct Type

Struct can be nested by creating a Struct type using other Struct types as the type for the fields of Struct. Nesting one struct within another can be a useful way to model more complex structures.

Use Field Tags in the Definition of Struct Type

During the definition of a struct type, optional string values may be added to each field declaration.

The tags are represented as raw string values (wrapped within a pair of `` ) and ignored by normal code execution.

Add Method to Struct Type

You can also add methods to struct types using a method receiver . A method EmpInfo is added to the Employee struct.

Assign Default Value for Struct Field

Method of assigning a custom default value can be achieve by using constructor function. Instead of creating a struct directly, the Info function can be used to create an Employee struct with a custom default value for the Name and Age field.

This is a technique rather than something that is part of the Golang specification.

Find Type of Struct

The reflect package support to check the underlying type of a struct.

Comparing Structs with the Different Values Assigned to Data Fields

Structs of the same type can be compared using comparison operator.

Copy Struct Type Using Value and Pointer Reference

r2 will be the same as r1 , it is a copy of r1 rather than a reference to it. Any changes made to r2 will not be applied to r1 and vice versa. When r3 is updated, the underlying memory that is assigned to r1 is updated.

As both r1 and r3 both reference the same underlying memory, their values are the same. Printing the values of r3 and r1 shows that the values are the same.

Most Helpful This Week

Go by Example : Structs

Next example: Methods .

by Mark McGranaghan and Eli Bendersky | source | license

Different Ways to Initialize Go structs

Categories:.

  8 minute read  

Many languages like Java, C#, etc. have constructors that help you instantiate an object and its properties.

Go does not have ‘constructors’ in the pure sense of the word. Let’s see what Go has instead.

Build-in options

Out-of-the-box Go gives us 2 ways to initialize structs - struct literals and the new build-in function. Let’s see what these look like for a simple struct named Person :

However, in this scenario the Person fields are un-exported, thus they cannot be used outside of the people package. We can easily mitigate this by exporting them:

But both of these options contain a big trade-off - now all the fields of the person can be viewed and changed by anyone. Also, we have no validation. For example, in this scenario, we can easily set the Age property to a negative value.

So what can we do if we don’t want to export the fields or enforce additional validation?

Constructor function

As I said in the beginning, Go does not have constructors. However, that does not mean we cannot define one ourselves. Let’s see how a user-defined constructor can look like:

With positional arguments

We can define a constructor function where the struct fields are positional arguments of the function:

This provides us 2 benefits:

  • We have validation for the age field. If someone tried to create a Person with a negative age, they will get a panic with a descriptive error of what they did wrong (we could have also returned an error, but this does not matter for the topic at hand). In the same manner, we could add validation for the name field (for example, that it’s not empty).
  • The Person internals are decoupled from the initialization logic. For example, we can add an isUnderage field to the struct and compute that based on age inside of the NewPerson function. The consumer of the function won’t have to be bothered with the logic behind this field, because we are taking care of it.

But it also has some downsides. If our Person had many string fields (for example - multiple names or addresses) this function would have looked like that:

and having a function with multiple parameters of the same type is a recipe for disaster. In this case, the danger is that the consumer of this function can easily misplace any of the parameters (for example, replace the first and last names) and they would have no compile-time check for that.

Another, even bigger issue than that is backward compatibility. Let’s say that we need to add additional fields to our Person struct. For example, salary (money rules the world, don’t they). We can easily add it:

However, this is a breaking change to the NewPerson method. If this were a library, all of the consumers would get compilation errors when they upgrade to the new version. This is definitely not ideal and could have a side-effect of your consumers screaming at you on Twitter.

Is there a way to make this without breaking change? Yes, of course. To do this we need to restructure our NewPerson function. Let’s see what are our options.

With Options struct

We can define PersonOptions struct that mirrors the Person but with exported field and pass this to NewPerson . Let’s see how this looks like:

This allows us to introduce new fields to Person as much as we like without breaking the contract of NewPerson .

However, there is another trade-off here: If we add a new field to Person (and respectively PersonOptions ) we cannot easily enforce that all consumers of NewPerson will set the new properties.

Of course, we can fail NewPerson if any of the new fields are missing, but this is actually a breaking change, not much better than the one in the first example (and even worse, because it will only be caught at runtime).

Another downside here is that it’s not obvious which fields from the PersonOptions structs are required and which are optional. The clearest way to communicate this to the consumers is via docstrings, which is not as obvious as just looking at the method signature (because who reads the docs, right).

Possible mitigation to this problem is if we define the required field in PersonOptions as value types and the optional ones as refs. For example:

This way the consumer can set the optional fields to nil and not bother with default values. It is also a bit more clear what is required and what is not.

Variadic function constructor

Alternative to that is to make our constructor a variadic function that accepts an arbitrary number of mutating functions. Then, the implementation of the method will run all the functions one by one on an instance of the struct which will be returned by the constructor. This means, we also need to provide a set of functions that will mutate the fields.

If you did not understand anything from this explanation, don’t worry. Here’s how the code looks like:

The downside here is that the amount of WithXXX functions are not obvious, and the consumers of the package would either have to search them in the package documentation or depend on their IDE autocomplete to show them the possible options.

In my opinion, it does not give you any benefits over the Options struct, but bring the downside that the options are not obvious.

Middle ground

A middle ground between constructor with required positional arguments and optional arguments would be to have the required fields for a given struct as positional arguments so that the consumer MUST pass them, and have everything else as optional parameters, which may be skipped.

There are 2 build-in ways to initialize a Go struct. Both are quite limited and more often than not they are not enough. That is why people came up with more sophisticated solutions (based on the built-in ones).

So what is the best option? Well, there isn’t one. All described approaches have their pros and cons. They depend on your use case and the way your code is meant to be used. As with everything in computer science, there is not a single correct solution or a silver bullet. It’s all a matter of the tradeoffs you are willing to make.

If you are writing a library that will be used by hundreds of other projects, backwards-incompatible changes will not be appreciated by your consumers, so you need to choose the more flexible options. If you’re working locally in a single codebase, signature changes can be beneficial, because they will enforce that all usages of the methods are adapted.

If you got to the end of the article, I just want you to know that I recently started this blog, and this is the first article in it. If it was useful for you, you learned something new, or you think it can be improved feel free to ping me on Twitter , LinkedIn or email . I would appreciate the feedback.

Structs in Go

Same as C, Go also supports struct types. This article will introduce the basic knowledge of struct types and values in Go.

Struct Types and Struct Type Literals

Each unnamed struct type literal starts with a struct keyword which is followed by a sequence of field definitions enclosed in a {} . Generally, each field definition is composed of a name and a type. The number of fields of a struct type can be zero.

The above struct type has three fields. The types of the two fields title and author are both string . The type of the pages field is int .

Some articles also call fields as member variables.

The size of a struct type is the sum of the sizes of all its field types plus the number of some padding bytes. The padding bytes are used to align the memory addresses of some fields. We can learn padding and memory address alignments in a later article .

The size of a zero-field struct type is zero.

Note, the tags of the X and Y fields in the above example are identical (though using field tags as this way is a bad practice).

We can use the reflection way to inspect field tag information.

The purpose of each field tag is application dependent. In the above example, the field tags can help the functions in the encoding/json standard package to determine the field names in JSON texts, in the process of encoding struct values into JSON texts or decoding JSON texts into struct values. The functions in the encoding/json standard package will only encode and decode the exported struct fields, which is why the first letters of the field names in the above example are all upper cased.

It is not a good idea to use field tags as comments.

Unlike C language, Go structs don't support unions.

All above shown struct types are unnamed. In practice, named struct types are more popular.

Only exported fields of struct types shown up in a package can be used in other packages by importing the package. We can view non-exported struct fields as private/protected member variables.

The field tags and the order of the field declarations in a struct type matter for the identity of the struct type. Two unnamed struct types are identical only if they have the same sequence of field declarations. Two field declarations are identical only if their respective names, their respective types and their respective tags are all identical. Please note, two non-exported struct field names from different packages are always viewed as two different names.

A struct type can't have a field of the struct type itself, neither directly nor recursively.

Struct Value Literals and Struct Value Manipulations

In Go, the form T{...} , where T must be a type literal or a type name, is called a composite literal and is used as the value literals of some kinds of types, including struct types and the container types introduced later.

Note, a type literal T{...} is a typed value, its type is T .

  • S{0, false} . In this variant, no field names are present but all field values must be present by the field declaration orders.
  • S{x: 0, y: false} , S{y: false, x: 0} , S{x: 0} , S{y: false} and S{} . In this variant, each field item is optional and the order of the field items is not important. The values of the absent fields will be set as the zero values of their respective types. But if a field item is present, it must be presented with the FieldName: FieldValue form. The order of the field items in this form doesn't matter. The form S{} is the most used zero value representation of type S .

If S is a struct type imported from another package, it is recommended to use the second form, to maintain compatibility. Consider the case where the maintainer of the package adds a new field for type S , this will make the use of first form invalid.

Surely, we can also use the struct composite literals to represent non-zero struct value.

For a value v of type S , we can use v.x and v.y , which are called selectors (or selector expressions), to represent the field values of v . v is called the receiver of the selectors. Later, we call the dot . in a selector as the property selection operator.

About Struct Value Assignments

Two struct values can be assigned to each other only if their types are identical or the types of the two struct values have an identical underlying type (considering field tags) and at least one of the two types is an unnamed type .

Struct Field Addressability

The fields of an addressable struct are also addressable. The fields of an unaddressable struct are also unaddressable. The fields of unaddressable structs can't be modified. All composite literals, including struct composite literals are unaddressable.

Note that the precedence of the property selection operator . in a selector is higher than the address-taking operator & .

Composite Literals Are Unaddressable But Can Take Addresses

Generally, only addressable values can take addresses. But there is a syntactic sugar in Go, which allows us to take addresses on composite literals. A syntactic sugar is an exception in syntax to make programming convenient.

In Field Selectors, Dereferences of Receivers Can Be Implicit

About struct value comparisons.

A struct type is comparable only if none of the types of its fields (including the fields with names as the blank identifier _ ) are incomparable .

Two struct values are comparable only if they can be assigned to each other and their types are both comparable. In other words, two struct values can be compared with each other only if the (comparable) types of the two struct values are identical or their underlying types are identical (considering field tags) and at least one of the two types is unnamed.

When comparing two struct values of the same type, each pair of their corresponding fields will be compared (in the order shown in source code). The two struct values are equal only if all of their corresponding fields are equal. The comparison stops in advance when a pair of fields is found unequal or a panic occurs . In comparisons, fields with names as the blank identifier _ will be ignored.

About Struct Value Conversions

Values of two struct types S1 and S2 can be converted to each other's types, if S1 and S2 share the identical underlying type (by ignoring field tags). In particular if either S1 or S2 is an unnamed type and their underlying types are identical (considering field tags), then the conversions between the values of them can be implicit.

  • values of type S0 can't be converted to the other four types, and vice versa, because the corresponding field names are different.
  • two values of two different types among S1 , S2 , S3 and S4 can be converted to each other's type.
  • values of the type denoted by S2 can be implicitly converted to type S3 , and vice versa.
  • values of the type denoted by S2 can be implicitly converted to type S4 , and vice versa.
  • values of the type denoted by S2 must be explicitly converted to type S1 , and vice versa.
  • values of type S3 must be explicitly converted to type S4 , and vice versa.

In fact, two struct values can be assigned (or compared) to each other only if one of them can be implicitly converted to the type of the other.

Anonymous Struct Types Can Be Used in Field Declarations

Anonymous struct types are allowed to be used as the types of the fields of another struct type. Anonymous struct type literals are also allowed to be used in composite literals.

Generally, for better readability, it is not recommended to use anonymous struct type literals in composite literals.

More About Struct Types

There are some advanced topics which are related to struct types. They will be explained in type embedding and memory layouts later.

The Go 101 project is hosted on Github . Welcome to improve Go 101 articles by submitting corrections for all kinds of mistakes, such as typos, grammar errors, wording inaccuracies, description flaws, code bugs and broken links.

If you would like to learn some Go details and facts every serveral days, please follow Go 101's official Twitter account @go100and1 .

  • Leanpub store , $19.99+ (You can get this book from this boundle which also contains 3 other books, with the same price) .
  • Amazon Kindle store, (unavailable currently) .
  • Apple Books store , $19.99 .
  • Google Play store , $19.99 .
  • Free ebooks , including pdf, epub and azw3 formats.
  • Color Infection (★★★★★), a physics based original casual puzzle game. 140+ levels.
  • Rectangle Pushers (★★★★★), an original casual puzzle game. Two modes, 104+ levels.
  • Let's Play With Particles , a casual action original game. Three mini games are included.
  • About Go 101 - why this book is written.
  • Acknowledgments
  • An Introduction of Go - why Go is worth learning.
  • The Go Toolchain - how to compile and run Go programs.
  • Introduction of Source Code Elements
  • Keywords and Identifiers
  • Basic Types and Their Value Literals
  • Constants and Variables - also introduces untyped values and type deductions.
  • Common Operators - also introduces more type deduction rules.
  • Function Declarations and Calls
  • Code Packages and Package Imports
  • Expressions, Statements and Simple Statements
  • Basic Control Flows
  • Goroutines, Deferred Function Calls and Panic/Recover
  • Go Type System Overview - a must read to master Go programming.
  • Value Parts - to gain a deeper understanding into Go values.
  • Arrays, Slices and Maps - first-class citizen container types.
  • Functions - function types and values, including variadic functions.
  • Channels - the Go way to do concurrency synchronizations.
  • Interfaces - value boxes used to do reflection and polymorphism.
  • Type Embedding - type extension in the Go way.
  • Type-Unsafe Pointers
  • Generics - use and read composite types
  • Reflections - the reflect standard package.
  • Line Break Rules
  • More About Deferred Function Calls
  • Some Panic/Recover Use Cases
  • Explain Panic/Recover Mechanism in Detail - also explains exiting phases of function calls.
  • Code Blocks and Identifier Scopes
  • Expression Evaluation Orders
  • Value Copy Costs in Go
  • Bounds Check Elimination
  • Concurrency Synchronization Overview
  • Channel Use Cases
  • How to Gracefully Close Channels
  • Other Concurrency Synchronization Techniques - the sync standard package.
  • Atomic Operations - the sync/atomic standard package.
  • Memory Order Guarantees in Go
  • Common Concurrent Programming Mistakes
  • Memory Blocks
  • Memory Layouts
  • Memory Leaking Scenarios
  • Some Simple Summaries
  • Value Conversion, Assignment and Comparison Rules
  • Syntax/Semantics Exceptions
  • Go Details 101
  • Go Tips 101
  • More Go Related Topics

cover image for article

Golang: Structs

Techstructive Blog @MeetGor21

Introduction

Moving on to the 9th part of the series, we will be understanding structs in golang. Structs are an important aspect of programming in Golang, they provide a way to define custom types and add functionality to them. We will be understanding the basics of operating on structs like declaration, initialization and adding functional logic into those structs.

Structs in Golang

Structs or Structures in Golang are the sequences or collections of built-in data types as a single type interface. Just like we have int, string, float, and complex, we can define our own data types in golang. They can consist of built-in data types as mentioned and also certain functions or methods which can be used to operate on them. Using structs we can create custom data types that can meet the specific requirements of our problem. We can define structs and later inside functions we can create instances of those structures.

Structures are like a template or blueprint representation of data. It doesn't hold the actual data in memory, it is just used to construct an object of that type. After defining a struct, we can create instances or objects of those structs. These instances actually hold data in memory in the run time, so we basically deal with objects in the actual program. We'll see certain concepts of creating instances, declaring and defining structs, accessing data from instances and so on in the following section of the article.

Declaring Struct

We can declare structs by using the keyword type followed by the name of the struct, after tha name, the struct keyword itself, and finally sets of parenthesis {} . Inside the parenthesis, we define the structure i.e. which type of data is to be stored and the name of those respective variables.

We have declared a struct or a custom data-type or a class(not really) in golang with the name Article that has few associated properties/variables inside of it. We have title as a string, is_published as a boolean, and words as an integer value. This constructs a simple type of golang which has a defined structure. We can further use this Article struct as a data type in the main function or any appropriate scope for actually assigning the structure memory at runtime.

Struct Naming Convention

There are a few things that we need to understand and make a note of, especially the naming convention.

  • The struct name should be capitalized if you want to make it publicly accessible.
  • The variable/properties names i.e. title , is_published , and words should be also capitalized if you want to make them accessible from the struct instance.

This might not be important right now but it is worth knowing for later use cases. Let's say we want to use a struct from other files or modules, for that the name of the struct in the file/script where the struct is defined should have the Capitalized convention. If you have a simple and single file script/program, you can keep it lowercased or camelCased .

Leaving that aside, for now, we will try to focus on the essence of the structs in golang.

Creating Instances/Objects of Structs

Now, after defining the struct we need to create instances or objects of them. This can be done in several ways like using Struct literal, Manual assignment, and using the new function. We'll look into each of them in this section.

Using struct literal

The most simplest and straightforward way to initialize a struct is to use the struct literal just like we did with Maps, Slices, and Arrays. We basically parse the values of the respective fields in the struct.

We have created the object or instance of the struct Article using the shorthand notation or the walrus := operator. Inside the {} braces, we can assign values but those values need to be in the same order as defined in the struct definition, else it gives a compilation error of type mismatch . So, here we have assigned the value title , is_published , and word as Golang Intro , true , and 2000 respective in that order.

Using Key-value pairs

We can also use the key-value notation for assigning values in the instance. With the previous method, we need to specify and thus initialize all the properties at once, but using this method we have a bit more flexibility.

Here, we have provided the key i.e. the variable name inside the struct, and then provided the value to it separated by a colon : . Using this way of initializing instances of struct we have better control and flexibility in providing a default value for that object. In the example above, we didn't initialize the property words but it already initialized to 0 since the object is created hence the memory allocation is completed, and thereby it needs to have a default value.

Using the new function

We can use the new function to create a new instance of a struct. Though we can't provide an initial value, using the new function all the properties are initialized with their respective default values. Further, if we want to modify the values, we can access each property (variables in struct) using the dot operator and assign the desired values.

We have used the new function to allocate memory for an instance of struct with the provided name. This function basically allocates all the properties of a default value and returns a pointer to that memory address. If we store the result of the new function in a variable object, we would get a pointer but we need the object itself, so we use * before the new function so as to de-reference the memory address from the pointer.

So, we have stored the default values in the newly created object of Article structure in django , this gives the default values like an empty string "" , default boolean value false and default integer value 0 . If we don't dereference the pointer and use it like djagno := new(Article) , thereby we get a pointer in that variable as &{ false 0} . Hence we use * before the new keyword.

Accessing/Assigning values to properties

We can now change the values of the properties in the object of the struct using the dot operator. We basically use the instance object name followed by a . and the property name to set its value.

So, here we have used the object name which is django , and access any property by name with the dot operator , thereby we set the value as per the requirement. Note, we have not used the := operator as the properties have already been initialized, we simply need to modify the default value.

Creating Functions associated to Structs

We can now move into creating functions in the struct, by adding functions/methods in structs we can incorporate a lot of functionality into the structure of our data type. For instance, we can set the value of a string as "Empty" or "NA" beforehand rather than empty string "" .

We define a function associated with a struct by providing the struct-name and a parameter name which can be just used inside of the function. Here, we have used (m Mail) so as to reference the object of the struct provided to it. This basically binds the function to the struct and hence it becomes a method of that struct.

Further, we can access the properties from the struct by their name using the dot separator. We are just checking whether the subject property in the instance is empty or not and simply printing text to the console. We are accessing the function and calling it with the syntax as instance_name.function_name() , here the function name is check_spam and the object name is mail_one for the first instance. Thereby we have called the function which is bounded to the instance of the struct. As we have accessed the function after the instance name the binding of the function i.e. the statements (m Mail) has taken the current instance and parsed it as the instance of the struct. Hence we are able to access the current instance's properties within the function/method.

Adding a return statement

By simply providing the return type and return statement with value, we can create functions of specific return types.

We have modified the check_spam function which returns a boolean value. If the subject is empty it returns true else it returns false. Also, we have added a function print_spam function which takes in a parameter as a boolean value and prints text according to the value. This is how we work with functions in structs. We have parsed the return value of the check_spam function as a parameter to the print_spam function.

Constructor in Structs

Constructors are special methods that are invoked when the instance of a struct is created i.e. the properties are assigned an initial value or default value. In this way, we can perform basic operations which we need to perform after the instantiation of the struct.

Golang does not have built-in constructors, but it is quite easy to create one. We simply need to create a function with an appropriate name(don't clash it with the struct name!!), by providing all the parameters that are in the struct so as to initialize them, and finally the return value as a reference to the struct instance.

We have created a function that is technically acting like a constructor as it sets a default value to the properties in the structure. We have struct Repository containing name as a string and file_count as an integer. We created a Constructor function named New_Repository that basically takes in the properties in the struct, remember they haven't been initialized yet as we are writing the constructor for the very purpose. We have to parse the parameters with the initial value and let it modify once we have created the instance.

That's it from this part. Reference for all the code examples and commands can be found in the 100 days of Golang GitHub repository.

So, from this part of the series, we are able to understand the basics of structs in golang. We covered declaration, definition, and adding methods in a struct. This gives a glimpse of Object-Oriented Programming in Golang. Thank you for reading. If you have any questions or feedback, please let me know in the comments or on social handles. Happy Coding :)

Golang: Maps

Vim for Competitive Programming

  • PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

last modified August 24, 2023

Go struct tutorial shows how to work with structures in Golang.

We use Go version 1.18.

A struct is a user-defined type that contains a collection of fields. It is used to group related data to form a single unit. A Go struct can be compared to a lightweight class without the inheritance feature.

Go struct definition

A struct is defined with the type keyword.

A new type is created with the type keyword. It is followed by the name of the type (User). The struct keyword indicates that we are creating a struct. Inside the curly brackets, we have a list of fields. Each field has a name and a type.

Go initialize struct

We show how to initialize struct types in Go.

A new User struct is created. The struct fields are initialized with the values provided between the curly brackets. In this case, the order of the fields is relevant.

We can provide both the field names and values. In this case, the order is not important. Note that the last comma is mandatory.

If we omit the values in the curly brackets, they are initialized to zero values.

Go struct simple example

The following is a Go struct simple example.

We define a User struct with three fields.

We declare the User struct.

We initialize the User struct.

We print the contents of the User struct.

Go struct access fields

The struct fields are accessed with the dot operator.

We create an empty User struct. We initialize the fields with values and read them using the dot operator.

Go anonymous struct

It is possible to create anonymous structs in Go. Anonymous structs do not have a name. They are created only once.

An anonymous struct is created only with the struct keyword. The declaration of the struct is followed by its initialization.

Go nested structs

Go structs can be nested.

In the code example, the Address struct is nested inside the User struct.

To access the fields of the nested struct, we access first the inner struct with the dot operator; then we access the respective fields.

Go struct promoted fields

The fields of a nested anonymous struct are promoted; that is, they are accessed without referring to the nested struct.

In the code example, we have a nested Address struct.

The User struct has a nested anonymous Address struct. The field does not have a name.

The city and country fields are promoted. They are accessed by directly referring to the parent struct.

Go struct functions fields

The struct fields can be functions.

In the code example, we have the User struct. Its info field is a function called Info .

Go struct pointer

A pointer to the struct can be created with the & operator or the new keyword. A pointer is dereferenced with the * operator.

In the code example, we create a pointer to the Point struct.

The & operator returns a pointer to the Point structure.

A pointer is dereferenced with the * operator. Go also allows to use the dot operator directly.

Alternatively, we can create a pointer to a struct with the new keyword.

The example creates a new pointer to the User struct with the new keyword.

Go struct constructor

There are no built-in constructors in Go. Programmers sometimes create constructor functions as a best practice.

In the code example, we have the newUser constructor function, which creates new User structs. The function returns a pointer to the newly created struct.

Go struct is a value type

Go structs are value types. When we assign a struct variable to another struct variable, a new copy of the struct is created. Likewise, when we pass a struct to another function, the function receives a new copy of the struct.

In the code example, we assign a struct to another struct. Changing the fields of the new struct does not affect the original struct.

The two structs are distinct entities.

Comparing Go structs

Go structs are equal if all their corresponding fields are equal.

In the code example, we compare two Point structs.

Go export struct

Named structs that start with a capital letter are exported and accessible from outside their packages. Similarly, struct fields that start with a capital letter are exported. Struct names and fields starting with a small letter are visible only inside their package.

We create a new Go module with the go mod init command.

This is the project structure.

The Name and Occupation fields of the User struct are exported, while the age field is not.

The address struct is not exported. We cannot refer to it in the main.go file.

In the main.go file, we import the Name and Occupation fields from the exporting/model package.

Go create a slice of structs

In the following example, we create a slice of structs.

A User type is defined. Then we create an empty slice of User structs. We add elements to the slice with append .

Go filter slice of structs

In the next example, we filter a slice of Go structures.

In the code example, we define a slice of users. We create a new slice that contains only programmers.

The User struct has three fields.

This is the original slice of User structures.

The filtered users/programmers are stored in the programmers slice.

We go over the users slice and add a current user to the programmers slice only if the user satisfies the isProgrammer predicate.

The IsProgrammer predicate returns true for all users whose occupation field equals to "programmer".

In this article we have covered structs in Golang.

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Go tutorials .

Trending now

What is kadane's algorithm, web developers vs. app developers: how they shape digital experiences, the ultimate guide to top front end and back end programming languages for 2021, what is fastapi: a thorough manual for python's cutting-edge web system, difference between hardware and software, fibonacci series in java: explained with examples, 20 most popular programming languages to learn in 2023, list to string in python, super keyword in java: an ultimate guide, top 40 coding interview questions you should know, the supreme guide to learn go struct.

The Supreme Guide to Learn Go Struct

Table of Contents

Go does not follow traditional Object-Oriented Programming . Rather, Go possesses structures that hold a combination of data types . Go does not have class-object architecture as well. In this tutorial, you will learn about the struct type in Go programming with the help of examples.

Here's How to Land a Top Software Developer Job

Here's How to Land a Top Software Developer Job

What Is Struct?

In Go programming, a structure or struct is a user-defined type to store a collection of different fields into a single field. 

For example, suppose you have a player and want to store his name and age. You can create two variables, name, and age, to store the values. Now, suppose you have a football team and want to store the same information for each player. 

This is where struct comes into play. You can design a struct that stores the values of the name and age of each player.

Declaring a Struct

In the above snippet, the type keyword introduces a new type, followed by the name of the type (Player) and the keyword struct. The struct contains a collection of various fields inside the curly braces. Each field possesses a name and a type.

Go_Struct_1.

Note: You can make the snippet compact by combining the various fields of the same type, as shown in the below example:

Go_Struct_2.

Let's understand the declaration of the struct with the help of a program.

Creating Instances of Struct Types

To work with a struct, you need to create an instance of it. The var keyword initializes a variable and, using dot notation, values are assigned to the struct fields.

You must now create a struct type Player. 

Go_Struct_3

Here, you have assigned the values to the struct while creating an instance ply1.

You will specify the value for each field name. The order of the fields can vary. It need not be the same as the order of the field names declared in the struct type.

Secondly, you will define an instance ply2 and assign value to struct variables

In ply2 struct, you have omitted the field names. In this case, it becomes necessary to maintain the order of fields as specified during the struct declaration. 

The above program gives the following output:

Go_Struct_4

Basics to Advanced - Learn It All!

Basics to Advanced - Learn It All!

Accessing Fields of Struct in Golang

You can access the individual fields of a struct using the struct instances.

Go_Struct_5

ply1.name in the above program accesses the name field of the ply1 struct. 

ply1.city accesses the city field of the ply1 struct. 

ply1.age accesses the age field of the ply1 struct. 

You have also modified the age of the player. 

This program prints as follows:

Go_Struct_6.

You have seen through the examples that it would become quite tedious to keep using built-in data types. Therefore, you use the user-defined struct type to store complex data structures .

If you aim to build a software development career, you can check the Post-Graduate Program in Full Stack Development by Simplilearn. It can be the ideal solution to help you develop your career in the right direction.

In case you have queries or would like to provide your input to our editorial team regarding this “The Supreme Guide to Go Struct” tutorial, feel free to use the comments section below. Our team of SMEs will get back to you soon!

Find our Post Graduate Program in Full Stack Web Development Online Bootcamp in top cities:

About the author.

Simplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

Recommended Programs

Post Graduate Program in Full Stack Web Development

Full Stack Web Developer - MEAN Stack

*Lifetime access to high-quality, self-paced e-learning content.

Basics of C++ Struct: Syntax, Creating Instance, Accessing Variables, and More

Basics of C++ Struct: Syntax, Creating Instance, Accessing Variables, and More

Recommended resources.

Python Interview Guide

Python Interview Guide

The Supreme Guide to Golang Maps

The Supreme Guide to Golang Maps

The Supreme Guide to Golang Interface

The Supreme Guide to Golang Interface

Tableau Interview Guide

Tableau Interview Guide

Go Programming Language: An Introduction

Go Programming Language: An Introduction

The Supreme Guide to Understand the Golang Rest API

The Supreme Guide to Understand the Golang Rest API

  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

IMAGES

  1. Golang Tutorial Structs And Receiver Methods 2020 A Complete Guide To

    struct assignment golang

  2. Golang Tutorial Structs And Receiver Methods 2020 A Complete Guide To

    struct assignment golang

  3. Golang Structs Example

    struct assignment golang

  4. Structs in Go (Golang) : A Comprehensive Guide

    struct assignment golang

  5. GoLang Tutorial

    struct assignment golang

  6. GoLang Tutorial

    struct assignment golang

VIDEO

  1. 5 Struct Ops Type Traits

  2. Cap. 10

  3. struct in cpp

  4. Object Oriented Programming in Golang

  5. golang basics

  6. C++ Struct

COMMENTS

  1. What Is the Abbreviation for “assignment”?

    According to Purdue University’s website, the abbreviation for the word “assignment” is ASSG. This is listed as a standard abbreviation within the field of information technology.

  2. What Is a Deed of Assignment?

    In real property transactions, a deed of assignment is a legal document that transfers the interest of the owner of that interest to the person to whom it is assigned, the assignee. When ownership is transferred, the deed of assignment show...

  3. What Is a Notice of Assignment?

    A Notice of Assignment is the transfer of one’s property or rights to another individual or business. Depending on the type of assignment involved, the notice does not necessarily have to be in writing, but a contract outlining the terms of...

  4. Golang Structs Tutorial with Examples

    When you assign one struct variable to another, a new copy of the struct is created and assigned. Similarly, when you pass a struct to another

  5. Assign struct with another struct

    Is it possible to assign the req struct into to the u struct so that all the common fields will exist in the u struct? struct · go · Share.

  6. Create, initialize and compare structs

    Go. Create, initialize and compare structs. yourbasic.org/golang. Struct types; 2 ways to create and initialize a new struct; Compare structs. Struct types. A

  7. Struct in Golang, declaring and creating Struct Data Type

    Method of assigning a custom default value can be achieve by using constructor function. Instead of creating a struct

  8. Structs

    Go's structs are typed collections of fields. They're useful for grouping data together to form records. package main. import "fmt". This person struct type

  9. Struct Literals

    A struct literal denotes a newly allocated struct value by listing the values of its fields. You can list just a subset of fields by using the Name: syntax. (

  10. Different Ways to Initialize Go structs

    The Person internals are decoupled from the initialization logic. For example, we can add an isUnderage field to the struct and compute that

  11. Structs in Go

    Struct Types and Struct Type Literals · Struct Value Literals and Struct Value Manipulations · About Struct Value Assignments · Struct Field Addressability.

  12. Golang: Structs

    This can be done in several ways like using Struct literal, Manual assignment, and using the new function. ... $ go run struct.go {Golang Intro

  13. Go struct

    Go structs are value types. When we assign a struct variable to another struct variable, a new copy of the struct is created. Likewise, when we

  14. Structs in Go (Golang) : A Comprehensive Guide

    ... struct type. Secondly, you will define an instance ply2 and assign value to struct variables. In ply2 struct, you have omitted the field names.