Go Struct

Gayathri. B

 Go Structures (Structs)

In Go, a struct (short for structure) is a custom data type that groups together variables (called fields) of different types into a single unit. It is commonly used to represent records.

When to Use Structs

  • Use arrays to store multiple values of the same type.
  • Use structs to store multiple values of different types under one name.

Declaring a Struct

  • To declare a struct, use the type and struct keywords:

Example:

type StructName struct {
  field1 dataType
  field2 dataType
  ...
}

Example

type Person struct {
  name   string
  age    int
  job    string
  salary int
}

Tip: name and job are strings, while age and salary are integers.

Accessing Struct Fields

  • Use the dot (.) operator to access individual fields of a struct.

Example:

package main
import "fmt"
type Person struct {
  name   string
  age    int
  job    string
  salary int
}
func main() {
  var person1 Person
  var person2 Person
  // Assign values
  person1.name = "Hege"
  person1.age = 45
  person1.job = "Teacher"
  person1.salary = 6000
  person2.name = "Cecilie"
  person2.age = 24
  person2.job = "Marketing"
  person2.salary = 4500
  // Print person1
  fmt.Println("Name:", person1.name)
  fmt.Println("Age:", person1.age)
  fmt.Println("Job:", person1.job)
  fmt.Println("Salary:", person1.salary)
  // Print person2
  fmt.Println("Name:", person2.name)
  fmt.Println("Age:", person2.age)
  fmt.Println("Job:", person2.job)
  fmt.Println("Salary:", person2.salary)
}

Output:

Name: Hege
Age: 45
Job: Teacher
Salary: 6000
Name: Cecilie
Age: 24
Job: Marketing
Salary: 4500

Passing Structs to Functions

  • You can pass structs as arguments to functions.

Example:

package main
import "fmt"
type Person struct {
  name   string
  age    int
  job    string
  salary int
}
func printPerson(p Person) {
  fmt.Println("Name:", p.name)
  fmt.Println("Age:", p.age)
  fmt.Println("Job:", p.job)
  fmt.Println("Salary:", p.salary)
}
func main() {
  person1 := Person{"Hege", 45, "Teacher", 6000}
  person2 := Person{"Cecilie", 24, "Marketing", 4500}
  printPerson(person1)
  printPerson(person2)
}

Output:

Name: Hege
Age: 45
Job: Teacher
Salary: 6000
Name: Cecilie
Age: 24
Job: Marketing
Salary: 4500

Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send