How to Create Struct in Go: Syntax and Examples
In Go, you create a
struct using the type keyword followed by the struct name and its fields inside curly braces. Structs group related data together, like a blueprint for an object.Syntax
A struct in Go is defined using the type keyword, followed by the struct name and the keyword struct. Inside curly braces, you list the fields with their names and types.
- type: declares a new type
- StructName: the name of your struct
- Fields: variables inside the struct with a name and type
go
type StructName struct {
Field1 Type1
Field2 Type2
}Example
This example shows how to create a struct called Person with fields for Name and Age. It then creates an instance and prints the values.
go
package main import "fmt" type Person struct { Name string Age int } func main() { p := Person{Name: "Alice", Age: 30} fmt.Println("Name:", p.Name) fmt.Println("Age:", p.Age) }
Output
Name: Alice
Age: 30
Common Pitfalls
Common mistakes include forgetting to capitalize struct fields if you want to access them from other packages, or mixing up field names and types. Also, initializing structs without field names can cause errors if the order is wrong.
Always use field names when creating structs to avoid confusion.
go
package main import "fmt" type Person struct { Name string Age int } func main() { // Wrong: order matters and can cause bugs // p := Person{"Alice", 30} // Right: use field names for clarity p := Person{Name: "Alice", Age: 30} fmt.Println(p) }
Output
{Alice 30}
Quick Reference
| Concept | Description |
|---|---|
| type | Keyword to declare a new struct type |
| StructName | Name of the struct type |
| Field | Name and type of each data element inside the struct |
| Initialization | Use field names for safe struct creation |
| Access | Use dot notation (e.g., structVar.Field) to access fields |
Key Takeaways
Use the type keyword followed by struct to define a struct in Go.
Always initialize structs using field names to avoid errors.
Capitalize struct fields to make them accessible outside the package.
Access struct fields using dot notation.
Structs group related data and help organize your code clearly.