WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Go · Basic · question 7 of 100

What is a struct in Go? Could you provide a simple example of a struct?

📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

A struct in Go is a composite data type that groups together variables under one name, making it easier to manage and manipulate them. These variables within the struct are called fields and can have different data types. Structs are useful for creating custom data types, modeling real-world entities, and representing more complex data structures.

Here’s a simple example of a struct:

package main

import "fmt"

// Define a struct named 'Person'
type Person struct {
    Name string
    Age  int
    City string
}

func main() {
    // Create an instance of the 'Person' struct
    person1 := Person{"Alice", 25, "New York"}

    // Access and modify the fields of the struct
    fmt.Println(person1.Name) // Output: Alice
    person1.Age = 26
    fmt.Println(person1.Age)  // Output: 26

    // Another way to create an instance of the 'Person' struct
    person2 := Person{
        Name: "Bob",
        Age:  30,
        City: "London",
    }
    fmt.Println(person2) // Output: {Bob 30 London}
}

In this example, we defined a ‘Person‘ struct with three fields: ‘Name‘, ‘Age‘, and ‘City‘. We then created instances of the struct ‘person1‘ and ‘person2‘ and accessed and modified their fields.

Here’s the same struct:

type Person struct {
    Name string
    Age  int
    City string
}
func main() {
    person1 := Person{"Alice", 25, "New York"}
    fmt.Println(person1.Name) // Output: Alice
    person1.Age = 26
    fmt.Println(person1.Age)  // Output: 26

    person2 := Person{
        Name: "Bob",
        Age:  30,
        City: "London",
    }
    fmt.Println(person2) // Output: {Bob 30 London}
}
Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Go interview — then scores it.
📞 Practice Go — free 15 min
📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

All 100 Go questions · All topics