Entenda Ponteiros, simples e facil com Go
Lidar com ponteiros pela primeira vez assusta quem vem de linguagens como JavaScript, Python ou Java, onde a gestão de memória é automática Mas a ideia é mais simples do que parece. O que são ponteiros? Toda variável ocupa um espaço na memória, e esse espaço possui um endereço. Um ponteiro é uma variável que guarda o endereço de outra variável , em vez de guardar diretamente o seu valor. x := 10…
Dealing with pointers for the first time can be daunting for those coming from languages like JavaScript, Python, or Java, where memory management is automatic. However, the concept is simpler than it appears. A pointer is a variable that holds the address of another variable, rather than the value itself. When we declare a variable, it occupies a certain amount of memory, and that memory has an address.
In Go, a pointer to a variable is declared using the '&' operator. For example, if we have a variable 'x' set to 10, we can create a pointer 'p' that points to 'x' by using '&x'. When we print the value pointed to by 'p' using '*p', it outputs 10, indicating that 'p' is indeed pointing to 'x'.
The two crucial operators related to pointers are '&', which retrieves the address of a variable, and '*', which accesses or modifies the value pointed to by a pointer. '*' is also used to indicate that a variable is of pointer type.
So, why use pointers? They are particularly useful when we need to work with the same instance of data without making unnecessary copies. Consider this function:
```go
func changeName(user *User) {
user.Name = "João"
}
```
Here, we pass the address of a 'User' object to the function. Inside the function, we modify the 'Name' field of the 'User' object. The original object is changed because the function has access to the original memory location through the pointer.
In contrast, if we didn't use a pointer:
```go
func changeName(user User) {
user.Name = "João"
}
```
The function would receive a copy of the 'User' object, and changes made inside the function would not affect the original object.
A real-world example is using a single instance of a database in an API. We can create one database connection and reuse it across different repositories:
```go
db, _ := sql.Open("postgres", dsn)
userRepo := NewUserRepository(db)
orderRepo := NewOrderRepository(db)
```
Both `userRepo` and `orderRepo` can share the same instance of the database. In Go, the general rule is to use values by default. However, we use pointers when we need to share or modify the same instance, represent a nil/null value, avoid a relevant or large copy, or simply to indicate that a variable is of pointer type.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.