struct
Basics of Struct
Struct can be used to define custom data types in Go. Often times, we can not handle the real world information using the standard data types which come with languages. While it is not impossible, it is highly inefficient. For example, in an eCommerce application, we have the ShoppingCart in which we put products for checkout.
type Product struct {
name string
itemID int
cost float32
isAvailable bool
inventoryLeft int
}There are a lot of attributes of Product, its name, the ID used internally, the cost, number of the products in stock, etc.
nameis astringused to store a product's name.itemIDis anintused to store for reference.costis afloat32of the item.isAvailableis aboolwhich is true if the item is in stock, false otherwise.inventoryLeftis anintof the number of products left in stock.
Initializing
// define goBook as a Product type
var goBook Product
// assign "Webapps in Go" to the field 'name' of goBook
goBook.name = "Webapps in Go"
// assign 10025 to field 'itemID' of goBook
goBook.itemID = 10025
// access field 'name' of goBook
fmt.Printf("The product's name is %s\n", goBook.name)There are three more ways to define a struct.
Assign initial values by order
goBook := Product{"Webapps in Go", 10025}
Use the format
field:valueto initialize the struct without order
goBook := Product{name:"Webapps in Go", itemID:10025, cost:100}
Define an anonymous struct, then initialize it
p := struct{name string; age int}{"Amy",18}
Let's see a complete example.
file: code/Struct/Book/struct.go
Embedded fields in struct
In the earlier chapter, we saw how to define a struct with field names and type. Embedded fields can be thought of as subclass and superclass in Object oriented programming.
When the embedded field is a struct, all the fields in that struct will implicitly be the fields in the struct in which it has been embedded.
Let's see one example.
file: code/Struct/Human/human.go

We see that we can access the age and name fields in Student just like we can in Human. This is how embedded fields work. We can even use Student to access Human in this embedded field!
All the types in Go can be used as embedded fields.
file: code/Struct/Skills/skills.go
In the above example, we can see that all types can be embedded fields and we can use functions to operate on them.
When we embed Human inside Employee, if Human and Employee have the phone field, then it isn't a problem. Because we access Employee's phone as Employee.Phone, but since Human is an embedded field inside Employee, we access Human's phone as Employee.Human.Phone
file: code/Struct/Employee/employee.go
Links
Last updated
Was this helpful?