What are Go Structs? (golang)

Sean Dever
2 min readNov 22, 2020

Most programming languages typically follow one of two styles, Functional programming(software construction by creating pure functions) or Object-oriented programming(a class-based structure working primarily with objects). Go is a multi-paradigm programming language which means that it’s a language capable of doing both. But Go does not have classes so how could we do anything object-orient related? Go has Structs that function a lot like classes in other languages.

Creating a Struct

To initiate a struct we use the keyword type, the name you wish to call the struct, the keyword struct accompanied by some curly braces.

type Superhero struct {
firstName string
lastName string
planet string
age int
powers []string
}

In the example above, we are creating a Superhero struct and within it lies attributes a superhero could have accompanied by the datatype allowed for that attribute. So now that we’ve set up our struct, let's create our first instance of a superhero.

wonderWoman := Superhero{
firstName: "Diana",
lastName: "Prince",
planet: "Earth-Two",
age: 800,
powers: []string{
"Super Strength",
"Telepathy",
"Astral Projection",
},
}

Simple as that! Now if we wanted to access specific pieces of data within the superhero we would use the “.” operator.

fmt.Println(wonderWoman.firstName) //Dianafmt.Println(WonderWoman.powers[1]) //Telepathy

Anonymous Struct

That isn’t the only way we can create structs. We can create anonymous structs. We aren’t able to create these within the package level because it is a struct with no name(hence being called anonymous). So the way we would make these are within a variable.

myDog := struct {
name string
breed string
age int
}{name: "Bro", breed: "Chihuahua", age: 10}

What are the use cases for an anonymous struct? One way is: say if we only needed to create a struct where we only plan to have one instance of it. Instead of creating a struct on the package level, we can create it within a variable like the example above.

Embedding

Go does not use inheritance as Object-oriented programming languages do. Go does have a feature called composition through embedding which acts like inheritance.

One other thing to point out about structs is unlike maps, structs are value types so you can assign a variable to an existing struct instance and it will not overwrite the original instance, it will create a literal copy of it. You can use the “&” operator and make it a pointer if you so wish. Structs are a great tool that almost every go program uses at least one. It also allows us to use validations through the use of tags. As always thanks for reading, hope you enjoyed this one! Happy Coding!

--

--