Go, Software Development

Golang Struct With Functions

It is common to see Golang Struct with functions, and it is the closest we can get at imitating OOP classes. Other than that, Golang is a procedural language.

Defining a Struct

We need to define a struct type before creating functions and linking them to a Golang struct. For example, consider the following codes.

We have a Person Golang struct with three properties – lastName, firstName, and id.

How to Define Struct Functions

With the Golang struct definition, we can now define functions that belong to the struct. For instance, consider the following codes.

We need an instance of the Golang struct to work with these functions, and there are three ways to declare and initialize a struct variable. For example, consider the following Golang codes within the main function. First, we declare and initialize a variable. Then, we run the functions from the struct.

We get the following output when we run the whole source code file.

Struct Passes Itself as Argument to Functions

To create struct functions, we define them to receive a single parameter of a struct type. But we specify the parameter before the function name. Meanwhile, we specify normal parameters after the function name. So, we have two lists of parameters in the function definition – one for the Golang struct type (or any type) we want the function to be part of, which comes before the function name, and another for the usual function parameters that come after the function name.

The Caveat

Although the codes work, there is one problem with them. When our Golang codes reach a point where we need to update the struct properties, the values will never change even when we explicitly set them. Why is that? Because Golang passes argument by value, the rule applies to parameters that go before and after the function name in its definition.

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like