# How to fix the "fieldalignment: struct with 32 pointer bytes could be 24 (govet)"

# Golang Field Alignment and structure size optimization

Since you're here already, I suppose you code in `Golang` and you're googling for a solution for a linter error mentioned in the article's title.

I won't go into detail when it comes to a memory management and field alignement in `Go`, because that's not the subject of this post. You can read more on that in [Golang Field Alignment](https://medium.com/@didi12468/golang-field-alignment-2e657e87668a) article.

Let's consider having a `struct`s like this:

```go
// Valid struct.
type Address struct {
	Name    string
	Street  string
	ZipCode string
	City    string
}

// Struct with misaligned fields.
type User struct {
	ID      int
	Name    string
	Address Address
}
```

`Address` contains all fields aligned, while the `User` `struct` not. What happens next?

# Problem

When running a linter on your codebase, you can get errors that looks similarly to this:

```bash
golangci-lint run ./...
fieldalignment.go:3:11: fieldalignment: struct with 80 pointer bytes could be 72 (govet)
type User struct {
          ^
```

Long story short is that your `struct`'s fields are in the wrong order and are using more memory than they could (again, see [Golang Field Alignment](https://medium.com/@didi12468/golang-field-alignment-2e657e87668a)).

# Solution

Trying to manually fix the `struct`'s fields order might be a pain if there're more than two.

As a solution we have a tool for that - `fieldalignment`. All you need to do is to install the `fieldalignment` tool:

```bash
go install golang.org/x/tools/go/analysis/passes/fieldalignment/cmd/fieldalignment@latest
```

And fix the code:

```bash
~/go/bin/fieldalignment -fix PATH
```

`fieldalignment` command does all the changes by itself. We end up with aligned fields in our `struct`, which now looks like this:

```go
// Struct with aligned fields.
type User struct {
	Address Address
	Name    string
	ID      int
}
```

Now you can run the linter once again and focus on other issues :P

# Sources

If you eager for more information, pls check:

* [Golang Field Alignment](https://medium.com/@didi12468/golang-field-alignment-2e657e87668a)
    
* [Examine Go source code](https://pkg.go.dev/cmd/vet)
    
* [Run linters from Go code](https://github.com/surullabs/lint)
