Allocation of structs on stack and heap in Go: how is it related to garbage collection?
Hello everyone! I've just started learning Go after C++ and Java, and I'm very confused about memory allocation for structs. In C++, I'm used to explicitly controlling whether I create an object on the stack (`MyClass obj;`) or on the heap (`MyClass* obj = new MyClass();`). In Java, everything is always on the heap, with references on the stack.
But in Go, I see that structs can be created as `myStruct := MyStruct{}` (seemingly on the stack) and as `myStruct := &MyStruct{}` (seemingly on the heap). And Go has a garbage collector. I'm completely confused.
For example, I have this code:
```go
type User struct {
Name string
Age int
}
func createUser(name string, age int) *User {
u := User{Name: name, Age: age}
return &u // Returning a pointer to a local variable!
}
```
In C++, this would be undefined behavior (dangling pointer).