Skip to main content

Go Structures

A struct (short for structure) combines several members, which can have different data types, into one variable.

An array also holds many values in one variable, but they must all share one data type. A struct has no such restriction.

That makes structs handy for keeping related data together as records.


Declare a Struct

Declaring a struct in Go takes two keywords: type and struct.

Tip: The members of Person don't all share a type. name and job are strings, while age and salary are integers.

Struct Syntax

main.go
type struct_name struct {
  member1 datatype;
  member2 datatype;
  member3 datatype;
  ...
}

Struct Declaration

main.go
type Person struct {
  name string
  age int
  job string
  salary int
}

Access Struct Members

To reach a member of a struct, write the struct variable's name, then the dot operator (.), then the member's name. Here it is used both to set and to read the members of two variables.

Example

Prompt
Declare a Person struct with name, age, job, and salary fields. Create two Person variables, set their fields, and print each field using the dot operator.
Output: Go program and captured output

Pass Struct as Function Arguments

A struct can also be passed to a function as an argument. Here printPerson() receives a Person and prints its members, so the printing code doesn't have to be repeated.

Example

Prompt
Pass a Person struct to a function called printPerson that prints all of its fields. Create two persons and call the function for each.
Output: Go program and captured output