Sobes.tech
Junior — Middle

How is the transfer of elements between functions and structures implemented in Golang?

sobes.tech AI

Answer from AI

In Go, passing elements between functions and structures can be done in two main ways: by value and by pointer.

  • Passing by value: the structure or variable itself is copied, and changes inside the function do not affect the original.
  • Passing by pointer: the address of the structure or variable is passed, allowing the function to modify the original data.

Example:

package main
import "fmt"

type Person struct {
    Name string
    Age  int
}

func updateByValue(p Person) {
    p.Age = 30 // only the copy will change
}

func updateByPointer(p *Person) {
    p.Age = 30 // the original will change
}

func main() {
    person := Person{Name: "Ivan", Age: 25}
    updateByValue(person)
    fmt.Println(person.Age) // 25

    updateByPointer(&person)
    fmt.Println(person.Age) // 30
}

Thus, if you need to modify data inside a function, pass a pointer to the structure. If no modifications are needed, you can pass by value.

How is the transfer of elements between functions and… - sobes.tech