Go struct programs group related data into one type, such as an employee with a name, salary and department, or an order with items and a total. Structs are how Go models real things, so you will use them in every project. In this post, you will write fourteen struct programs with their exact output, covering methods, nested structs, embedding, constructors and JSON tags, followed by the struct questions interviewers ask most.
You should know functions from our Go function programs and slices from our Go slice programs. For the theory, read the Go structs guide for beginners and Go methods and receivers. All programs were tested on Go 1.27.
What are Go Struct Programs?
Go struct programs define a struct type, which is a named group of fields. Each field has a name and a type. You then create values of that type and attach methods, which are functions tied to the struct.
Think of a struct as a form. An employee form has boxes for Name, Department and Salary. The struct type is the blank form, and each struct value is one filled-in copy.
Why Go Struct Programs Matter
Go has no classes, so structs do that job. For example, an API request body is a struct, a database row maps to a struct and a config file loads into a struct. So Go struct programs are the base for almost everything in Levels 5 and 6.
- Modelling data: users, orders, products and invoices are all structs.
- Behaviour: methods give each struct its own actions.
- Interviews: value vs pointer receivers, embedding and comparison are common questions.
How Go Struct Programs Work
You declare a type with type Name struct { ... }. Then you create values with a literal, read fields with a dot, and call methods with the same dot syntax. When you assign a struct, Go copies all its fields.

The table below shows the main ways to create a struct value.
| Way | Example | Notes |
|---|---|---|
| Named fields | Employee{Name: “Asha”, Salary: 50000} | Clear and safe, the usual way |
| Positional | Employee{“Asha”, “IT”, 50000} | Breaks when fields change |
| Zero value | var e Employee | All fields at zero |
| Pointer | &Employee{Name: “Asha”} | Ready for pointer methods |
| Constructor | NewEmployee(“Asha”, 50000) | Adds checks and defaults |
Basic Go Struct Programs
These first Go struct programs create values and read their fields.
Program 1: A Book, the Simplest of Go Struct Programs
Start with the smallest possible struct. It has two fields, and you read each one with a dot.
package main
import "fmt"
// Book holds the title and page count of one book.
type Book struct {
Title string // the name of the book
Pages int // how many pages it has
}
func main() {
// Create a Book value and fill in both fields by name.
book := Book{Title: "Learn Go", Pages: 250} // := creates a new variable
// Read each field with a dot.
fmt.Println("Title:", book.Title)
fmt.Println("Pages:", book.Pages)
// Change a field the same way.
book.Pages = 300
fmt.Println("New page count:", book.Pages)
}
Title: Learn Go
Pages: 250
New page count: 300
First, type Book struct describes the shape of the data. Then Book{...} makes one real book with values. You read a field with book.Title and change it with book.Pages = 300.
Program 2: Define and Print a Struct
package main
import "fmt"
// Employee describes one person who works in a company.
type Employee struct {
Name string
Dept string // Dept is short for department
Salary int
}
func main() {
employee := Employee{Name: "Asha", Dept: "IT", Salary: 65000}
var empty Employee // no values given, so every field is at its zero value
fmt.Println(employee) // prints only the values
fmt.Printf("%+v\n", employee) // %+v prints field names too
fmt.Println(employee.Name, "earns", employee.Salary)
fmt.Printf("%+v\n", empty)
}
{Asha IT 65000}
{Name:Asha Dept:IT Salary:65000}
Asha earns 65000
{Name: Dept: Salary:0}
Println shows only the values inside curly braces. The %+v verb also shows each field name, which helps when you debug. An empty struct value has every field at its zero value: “” for strings and 0 for ints.
Program 3: Student Marks with a Slice of Structs
package main
import "fmt"
// Student holds a name and a list of marks.
type Student struct {
Name string
Marks []int // a slice that can hold any number of marks
}
// Average returns the mean of the student's marks.
func (student Student) Average() float64 {
// Step 1: add up all the marks.
total := 0
for _, mark := range student.Marks { // range walks over each mark; _ skips the index
total += mark
}
// Step 2: divide by the number of marks.
return float64(total) / float64(len(student.Marks))
}
func main() {
class := []Student{
{"Ravi", []int{78, 85, 90}},
{"Meera", []int{92, 88, 95}},
{"Kiran", []int{60, 72, 68}},
}
for _, student := range class {
fmt.Printf("%-6s %.1f\n", student.Name, student.Average()) // %-6s pads the name, %.1f shows one decimal
}
}
Ravi 84.3
Meera 91.7
Kiran 66.7
Average is a method with a value receiver, written (student Student). It adds the marks, then divides by how many there are. The method only reads the data, so working on a copy is fine.
Methods in Go Struct Programs
In Go struct programs, methods let a struct act on its own data.
Program 4: A Simple Method for Rectangle Area
Here is the easiest kind of method. It reads two fields and returns one answer.
package main
import "fmt"
// Rectangle stores the width and height of a shape.
type Rectangle struct {
Width int
Height int
}
// Area returns width times height.
func (rectangle Rectangle) Area() int {
return rectangle.Width * rectangle.Height
}
func main() {
room := Rectangle{Width: 4, Height: 3}
fmt.Println("Area of the room:", room.Area()) // call the method with a dot
}
Area of the room: 12
The part (rectangle Rectangle) before the name makes Area belong to the Rectangle type. Inside the method, rectangle is the value you called it on. So room.Area() multiplies 4 by 3 and returns 12.
Program 5: Value vs Pointer Receivers
package main
import "fmt"
// Account is a simple bank account.
type Account struct {
Owner string
Balance int
}
// DepositCopy gets a copy of the account, so the change is lost.
func (account Account) DepositCopy(amount int) {
account.Balance += amount // changes a copy only
}
// Deposit gets a pointer (*Account), so it changes the real account.
func (account *Account) Deposit(amount int) {
account.Balance += amount // changes the real account
}
func main() {
myAccount := Account{Owner: "Asha", Balance: 1000}
myAccount.DepositCopy(500)
fmt.Println(myAccount.Balance) // still 1000
myAccount.Deposit(500) // Go passes &myAccount for you
fmt.Println(myAccount.Balance) // now 1500
}
1000
1500
A value receiver gets a copy, so its changes are lost. A pointer receiver gets the address, so it changes the original. Go adds the & for you when you call myAccount.Deposit.
Program 6: A String Method for Nice Printing
When a type has a String() string method, fmt uses it to print the value.
package main
import "fmt"
// Product is an item in a shop.
type Product struct {
Name string
Price float64
}
// String tells fmt how to print a Product.
func (product Product) String() string {
return fmt.Sprintf("%s (Rs %.2f)", product.Name, product.Price) // Sprintf builds a string instead of printing
}
func main() {
items := []Product{{"Notebook", 45}, {"Pen", 10.5}}
fmt.Println(items[0]) // fmt calls String() for you
fmt.Println(items) // it also works for every item in a slice
}
Notebook (Rs 45.00)
[Notebook (Rs 45.00) Pen (Rs 10.50)]
You never call String() yourself. Instead, fmt.Println sees the method and uses it. This is the fmt.Stringer interface, and we cover interfaces in depth later in this level.
Program 7: A Constructor with Validation
Go has no constructors, so we write a New... function that returns a ready value or an error.
package main
import (
"errors"
"fmt"
)
// User is a person with a name and an age.
type User struct {
Name string
Age int
}
// NewUser checks the input and returns a new User or an error.
func NewUser(name string, age int) (*User, error) {
// Step 1: the name must not be empty.
if name == "" {
return nil, errors.New("name is required") // nil means "no user"
}
// Step 2: the age must be sensible.
if age < 0 || age > 130 {
return nil, fmt.Errorf("invalid age %d", age)
}
// Step 3: all good, so return the address of a new User.
return &User{Name: name, Age: age}, nil // & gives a pointer to the new value
}
func main() {
user, err := NewUser("Meera", 28) // err is the error value, nil when all is fine
fmt.Println(*user, err) // *user reads the value the pointer points to
_, err = NewUser("", 20)
fmt.Println(err)
_, err = NewUser("Dev", 200)
fmt.Println(err)
}
{Meera 28} <nil>
name is required
invalid age 200
NewUser checks the name first, then the age. If a check fails, it returns nil and an error message. Returning a pointer is common for constructors, because the caller usually changes the value later.
Nested and Embedded Go Struct Programs
Go struct programs often hold other structs, which helps you model real data.
Program 8: Nested Struct for an Address
package main
import "fmt"
// Address is a place where someone lives.
type Address struct {
City string
Pincode string
}
// Customer has a name and a whole Address inside it.
type Customer struct {
Name string
Address Address // a struct inside a struct
}
func main() {
customer := Customer{
Name: "Kiran",
Address: Address{City: "Pune", Pincode: "411001"},
}
fmt.Println(customer.Name, "lives in", customer.Address.City) // two dots to reach the city
customer.Address.City = "Mumbai"
fmt.Printf("%+v\n", customer)
}
Kiran lives in Pune
{Name:Kiran Address:{City:Mumbai Pincode:411001}}
The Customer struct holds an Address field, which is itself a struct. You reach the inner field with two dots, as in customer.Address.City. Changing it works the same way.
Program 9: Embedding for Reuse
When you embed a struct without a field name, its fields and methods are promoted to the outer struct.
package main
import "fmt"
// Person has a name.
type Person struct {
Name string
}
// Greet returns a short hello message.
func (person Person) Greet() string {
return "Hi, I am " + person.Name
}
// Manager is a Person who also leads a team.
type Manager struct {
Person // embedded: no field name, only the type
TeamSize int
}
func main() {
manager := Manager{Person: Person{Name: "Ravi"}, TeamSize: 8}
fmt.Println(manager.Name) // Name comes from Person
fmt.Println(manager.Greet()) // Greet also comes from Person
fmt.Println(manager.Person.Name, manager.TeamSize)
}
Ravi
Hi, I am Ravi
Ravi 8
manager.Name and manager.Greet() work as if they belonged to Manager. This is composition, which Go uses instead of inheritance. See our Go struct embedding guide for more.
Program 10: Anonymous Struct for Quick Data
package main
import "fmt"
func main() {
// A struct with no type name, used only here.
point := struct {
X, Y int
}{3, 4}
fmt.Println(point.X*point.X + point.Y*point.Y)
// A list of test cases: an input number and the answer we expect.
tests := []struct {
input int
want bool
}{{2, true}, {3, false}, {10, true}}
for _, test := range tests {
isEven := test.input%2 == 0 // % gives the remainder
fmt.Println(test.input, isEven == test.want)
}
}
25
2 true
3 true
10 true
Here struct { ... }{...} defines the shape and fills it in one go. The loop checks if each input is even, then prints whether that matches want. Anonymous structs are perfect for one-off data like this, and you will see the pattern in table-driven tests.
Practical Go Struct Programs
The next Go struct programs show how copies and tags behave in real code.
Program 11: Compare and Copy Structs
package main
import "fmt"
// Point is a spot on a grid.
type Point struct{ X, Y int }
func main() {
first := Point{1, 2}
second := first // a full copy, not a link
second.X = 100 // changes only the copy
fmt.Println(first, second)
fmt.Println(first == Point{1, 2}, first == second) // == compares every field
}
{1 2} {100 2}
true false
Assigning second := first makes an independent copy, so changing second leaves first alone. Structs compare field by field when every field is comparable.
Program 12: Update a Struct Inside a Slice
package main
import "fmt"
// Task is one item on a to-do list.
type Task struct {
Title string
Done bool
}
func main() {
tasks := []Task{{"write code", false}, {"test", false}}
// Wrong way: task is a copy of each item.
for _, task := range tasks {
task.Done = true // changes a copy
}
fmt.Println(tasks)
// Right way: use the index to reach the real item.
for i := range tasks {
tasks[i].Done = true // changes the slice item
}
fmt.Println(tasks)
}
[{write code false} {test false}]
[{write code true} {test true}]
range gives a copy of each struct, so the first loop does nothing useful. The second loop uses the index i and writes to tasks[i] directly. That changes the real item in the slice.
Program 13: Struct Tags and JSON
Tags are small notes on fields. The encoding/json package reads them to choose JSON names.
package main
import (
"encoding/json"
"fmt"
)
// Order is a shop order that we turn into JSON.
type Order struct {
ID int `json:"id"` // JSON key will be "id"
Amount float64 `json:"amount"` // JSON key will be "amount"
Note string `json:"note,omitempty"` // skipped when empty
secret string // not exported, never in JSON
}
func main() {
order := Order{ID: 101, Amount: 499.5, secret: "x"}
data, _ := json.Marshal(order) // Marshal turns the struct into JSON bytes; _ ignores the error here
fmt.Println(string(data)) // convert the bytes to text to print them
}
{"id":101,"amount":499.5}
json.Marshal reads each tag and uses it as the key name. omitempty skips the empty note. The lower case secret field is not exported, so JSON never sees it. We go further with JSON in Level 5.
Program 14: Struct as a Map Key
package main
import "fmt"
// Cell is one square on a game board.
type Cell struct{ Row, Col int }
func main() {
board := map[Cell]string{} // a map with Cell keys and string values
board[Cell{0, 0}] = "X"
board[Cell{1, 1}] = "O"
fmt.Println(board[Cell{1, 1}], len(board))
_, taken := board[Cell{2, 2}] // taken is true only if the key exists
fmt.Println(taken)
}
O 2
false
A struct with comparable fields can be a map key. Here each Cell holds a row and a column, which makes a neat game board. The two-value lookup tells you if a square is already taken.
Value vs Pointer Receivers in Go Struct Programs
Choosing the receiver type is the most important design choice in Go struct programs. The diagram and table below compare the two.

| Feature | Value receiver (s T) | Pointer receiver (s *T) |
|---|---|---|
| Gets | A copy | The address |
| Can change fields | Only the copy | Yes, the original |
| Cost for big structs | Copies all fields | Cheap |
| Called on nil | No | Yes, if handled |
| Use when | Small, read-only types | You change data or the type is big |
A common rule is this: if any method needs a pointer receiver, use pointer receivers for all methods of that type, so the type behaves the same everywhere.
Common Mistakes in Go Struct Programs
- Changing a copy in range:
for _, task := range tasksgives copies, so use the index. - Value receiver for updates: changes vanish, so use
*Twhen a method changes fields. - Positional literals: adding a field breaks
Employee{"Asha", "IT", 50000}, so use field names. - Lower case fields and JSON: unexported fields are skipped by
encoding/json. - Comparing structs with slices: a struct with a slice or map field cannot use
==.
Best Practices for Go Struct Programs
- Use named fields in every struct literal.
- Write New functions that check input and set defaults.
- Keep receivers consistent, all value or all pointer for one type.
- Add a String method for types you print often.
- Prefer embedding to deep nesting when a type should reuse another type’s methods.
Go Struct Programs Interview Questions and Answers
These Go struct programs test rules that come up in almost every interview. Each program is complete, with real output from Go 1.27.
Struct Basics Questions
Q1. Does Go have classes and inheritance?
No. Go has structs for data and methods for behaviour. Instead of inheritance, it uses embedding (composition) and interfaces.
Q2. Why does this program not compile?
package main
import "fmt"
// Team has a name and a slice of member names.
type Team struct {
Name string
Members []string
}
func main() {
teamA := Team{"A", []string{"x"}}
teamB := Team{"A", []string{"x"}}
fmt.Println(teamA == teamB) // not allowed: Members is a slice
}
invalid operation: teamA == teamB (struct containing []string cannot be compared)
A struct can use == only when every field is comparable. Slices are not, so compare such structs with your own function or reflect.DeepEqual.
Q3. What does this program print?
package main
import (
"fmt"
"unsafe"
)
// Loose puts a big field between two small ones.
type Loose struct {
Active bool
Total int64
Valid bool
}
// Tight puts the big field first.
type Tight struct {
Total int64
Active bool
Valid bool
}
func main() {
// unsafe.Sizeof returns how many bytes a value takes in memory.
fmt.Println(unsafe.Sizeof(Loose{}), unsafe.Sizeof(Tight{}), unsafe.Sizeof(struct{}{}))
}
24 16 0
Go adds padding so the int64 lines up in memory. Putting large fields first saves space. An empty struct takes zero bytes, which is why map[string]struct{} is used for sets.
Q4. What is the zero value of a struct?
It is a struct where every field holds its own zero value. A zero struct is ready to use, which is why many Go types work without a constructor.
Method Questions
Q5. What does this program print?
package main
import "fmt"
// Counter keeps a running count.
type Counter struct{ count int }
// Increment adds one to the count (pointer receiver, so it changes the original).
func (counter *Counter) Increment() { counter.count++ }
// Value returns the current count (value receiver, read only).
func (counter Counter) Value() int { return counter.count }
func main() {
var counter Counter
counter.Increment()
counter.Increment()
pointer := &counter // pointer holds the address of counter
pointer.Increment()
fmt.Println(counter.Value(), pointer.Value())
}
3 3
Go converts between counter and &counter automatically when you call methods on a variable. Both names refer to the same counter, so both print 3.
Q6. What does this program print?
package main
import "fmt"
// Box holds a list of items.
type Box struct{ Items []string }
// Add has a value receiver, so it works on a copy of the box.
func (box Box) Add(item string) {
box.Items = append(box.Items, item) // append adds to the copy only
}
func main() {
box := Box{}
box.Add("pen")
fmt.Println(len(box.Items))
}
0
Add has a value receiver, so it appends to a copy of the struct. The original box.Items stays empty. A pointer receiver fixes this.
Q7. What happens when two embedded types have the same field?
package main
import "fmt"
// Engine and Wheel both have a field called ID.
type Engine struct{ ID int }
type Wheel struct{ ID int }
// Car embeds both of them.
type Car struct {
Engine
Wheel
}
func main() {
car := Car{Engine{1}, Wheel{2}}
fmt.Println(car.Engine.ID, car.Wheel.ID) // name the embedded type to pick one ID
}
1 2
Writing car.ID would be a compile error, because Go cannot tell which ID you mean. You must name the embedded type, as in car.Engine.ID.
Output Questions
Q8. What does this program print?
package main
import "fmt"
// Point is a spot on a grid.
type Point struct{ X, Y int }
// move gets a copy of the point.
func move(point Point) { point.X = 99 }
// movePtr gets the address of the point, so it changes the original.
func movePtr(point *Point) { point.X = 99 }
func main() {
point := Point{1, 1}
move(point)
fmt.Println(point) // unchanged
movePtr(&point) // pass the address with &
fmt.Println(point) // changed
}
{1 1}
{99 1}
move works on a copy, so the first print still shows {1 1}. movePtr gets the address, so it changes the real point to {99 1}.
Q9. What does this program print?
package main
import "fmt"
// Config holds server settings.
type Config struct {
Port int
Host string
}
func main() {
config := &Config{Port: 8080} // config is a pointer to a Config
fmt.Printf("%+v\n", config) // printing the pointer
fmt.Printf("%v\n", *config) // printing the value it points to
}
&{Port:8080 Host:}
{8080 }
Printing a pointer to a struct shows & in front. Printing *config shows the value itself.
Q10. Can a struct have a method and a field with the same name?
No. Go reports a compile error, because x.Name would be ambiguous. Rename one of them.
Q11. What are exported and unexported fields?
Fields that start with a capital letter are exported and can be used from other packages. Lower case fields are private to their package, and packages like encoding/json cannot see them.
Q12. What does this program print?
package main
import "fmt"
// Pair is a key with a number value.
type Pair struct {
Key string
Value int
}
func main() {
pairs := []*Pair{{"a", 1}, {"b", 2}} // a slice of pointers to Pair
for _, pair := range pairs {
pair.Value *= 10 // pair is a copy of the pointer, but it points to the real struct
}
fmt.Println(*pairs[0], *pairs[1])
}
{a 10} {b 20}
This time pair is a copy of a pointer, so it still points to the real struct. That is why the change sticks, unlike Program 12.
Practice Task
A bank account is a classic among Go struct programs. Create a BankAccount struct with Owner and Balance fields, and write Deposit, Withdraw and String methods. Withdraw should return an error if the balance is too low. Hint: use pointer receivers for the two methods that change the balance.
Official Resources
Quick Recap
- Go struct programs group related fields into one named type.
- Methods with value receivers work on copies, and pointer receivers change the original.
- Embedding promotes fields and methods, which Go uses instead of inheritance.
- Structs compare with
==only when every field is comparable. - Struct tags such as
json:"id"control how packages likeencoding/jsonsee fields.
What’s Next?
Next, we look closely at the addresses behind pointer receivers. Read Go pointer programs with output, with swap, linked updates and nil checks. For interview practice, see the Go structs interview questions.


