# Structs in Go

> Learn how structs work in Go, a type that groups fields of different types so you can define, initialize, access with dot syntax, and even nest them.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2022-09-18 | Topics: [Go](https://flaviocopes.com/tags/go/) | Canonical: https://flaviocopes.com/golang-structs/

A **struct** is a *type* that contains one or more variables. It’s like a collection of variables. We call them *fields*. And they can have differnet types.

Here’s an example of a struct definition:

```go
type Person struct {
	Name string
	Age int
}
```

Note that I used uppercase names for the fields, otherwise those will be *private* to the package and when you pass the struct to a function provided by another package, like the ones we use to work with [JSON](https://flaviocopes.com/json/) or database, those fields cannot be accessed.

Once we define a struct we can initialize a variable with that type:

```go
flavio := Person{"Flavio", 39}
```

and we can access the individual fields using the dot syntax:

```go
flavio.Age //39
flavio.Name //"Flavio"
```

You can also initialize a new variable from a struct in this way:

```go
flavio := Person{Age: 39, Name: "Flavio"}
```

This lets you initialize only one field too:

```go
flavio := Person{Age: 39}
```

or even initialize it without any value:

```go
flavio := Person{}

//or

var flavio Person
```

and set the values later:

```go
flavio.Name = "Flavio"
flavio.Age = 39
```

Structs are useful because you can group unrelated data and pass it around to/from functions, store in a slice, and more.

Once defined, a struct is a type like `int` or `string` and this means you can use it inside other structs too:

```go
type FullName struct {
	FirstName string
	LastName string
}

type Person struct {
	Name FullName
	Age int
}
```
