Passing Go Struct as Function Argument

A struct is a composite data type that groups together zero or more values with different types under a single name. Structs are used to define custom data types that represent complex objects with a set of properties. In Go, you can pass a struct as a function argument by value or by reference.

When a struct is passed by value, a copy of the entire struct is created and passed to the function. This can be inefficient for large structs as it requires copying a lot of data. To avoid this, you can pass a struct by reference using a pointer. This allows the function to modify the original struct directly.

Here’s an example that demonstrates how to pass a struct as a function argument:

type Employee struct {
    FirstName string
    LastName  string
    Age       int

func updateEmployee(emp *Employee, age int) {
    emp.Age = age

func main() {
    emp := Employee{"John", "Doe", 30}
    fmt.Println("Before update: ", emp)
    updateEmployee(&emp, 35)
    fmt.Println("After update: ", emp)

In the above example, we defined a struct called Employee with three fields: FirstName, LastName, and Age. We then defined a function called updateEmployee that takes a pointer to an Employee struct and an integer age. Inside the function, we update the Age field of the Employee struct using the pointer.

In the main function, we create an instance of the Employee struct and print its values. We then call the updateEmployee function with a pointer to the Employee struct and a new age value. Finally, we print the updated values of the Employee struct.

The output of the above code will be:

Before update:  {John Doe 30}
After update:  {John Doe 35}

As you can see, the Age field of the Employee struct was successfully updated using the updateEmployee function. By passing a pointer to the struct as a function argument, we were able to modify the original struct directly.

Follow us on social media
Follow Author