What are structs? Well structs are the foundation of Golang. If you are coming from PHP or Python or Ruby or any OOP programming language you can perceive these as classes but not exactly. In your typical class, you can define fields and functions as private or public or in-between. However, Golang does this a bit different.
Golang is different
How so? For one, if the variable name or the method name is capitalize, Go perceives this as an exported value. Therefore, if you are trying to access the struct or a method or any variable from a package in a different package, then this value needs to be capitalized in order to be used outside the package where it is defined. Now, with that said, the reverse is true. If the struct or the variable or the method is lowercase, then this makes it private
in a sense, meaning, it is only usable within the package that defined it. This however, is a subject for another time. Let us give an example on how to create a struct.
Structs the foundation of all
type Person struct {
Name string
LastName string
Age int
}
Go’s structs are typed collections of fields. They’re useful for grouping data together to form records
In the above example we have defined a Go struct that is named Person
, and it contains three fields or attributes that have their types defined next to them. The Name
and the LastName
are both of type string
, and Age
is of type int
.
// Initialize a variable using the var keyword
var mike Person
Person.Name = "Mike"
Person.LastName = "Doe"
Person.Age = 30
// Or you can just use short hand
john := Person{
Name: "John",
LastName: "Doe",
Age: 25,
}
In the above example, you are provided two ways you can initialize a variable with the same type, in our case Person
. The first example uses the var
reserved keyword to assign mike
as type Person
. The second variant uses short hand to do the assignment, but it also allows you to set the key values of the struct.
There are a limited number of predefined types that are available to your declared attributes. These values are:
- Built-in string type:
- string
- Built-in bool type:
- bool
- Built-in numeric types:
- int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, rune, uintptr, (byte)
- float32, float64
- complex64, complex128
In later articles, I will go over on how you can use structs and composition to add behavior to a struct. Here is a sneak preview of how we can add functionality to our Person
struct.
// SayHello
func (p *Person) SayHello() string {
return fmt.Sprintf("Hello world, from %s %s", p.Name, p.LastName)
}
Can you guess what is going on in this method?
Thank you for reading, Golang structs the foundation of all
. If you wish to play around with structs, you can do that here.