Junior — Middle
Kuidas toimub mälu eraldamine objektidele tarkvaras?
sobes.tech AI
Vastus AI-lt
In Go, memory allocation for objects is done automatically using the built-in garbage collector.
When you create an object, for example using new or a struct literal, memory is allocated on the heap or stack depending on the compiler's (escape analysis) analysis. If an object "escapes" the function, it is placed on the heap to preserve its lifecycle.
Example of object allocation:
type Person struct {
Name string
Age int
}
func main() {
p := &Person{Name: "Иван", Age: 30} // memory is allocated automatically
fmt.Println(p.Name)
}
Go manages memory automatically: it frees unused objects, reducing the risk of memory leaks and simplifying development.