Sobes.tech
Junior — Middle

What are the advantages and disadvantages of applying Reservation without using pointers?

sobes.tech AI

Answer from AI

In Go, using Reservation (assuming it refers to a struct or object Reservation) without pointers has its pros and cons.

Advantages:

  • Simplicity: passing and using values by copy simplifies understanding the code.
  • Safety: absence of pointers reduces the risk of errors related to null or dangling pointers.
  • Immutability: copies of data do not affect the original, which can be useful for preventing side effects.

Disadvantages:

  • Performance: copying large structs can be costly in terms of time and memory.
  • Lack of ability to modify the original data through a function if a copy is passed.
  • When shared access to data without copying is needed, pointers are more efficient.

Example:

 type Reservation struct {
    ID   int
    Name string
}

func updateReservation(r Reservation) {
    r.Name = "New Name" // only the copy will change
}

func main() {
    res := Reservation{ID: 1, Name: "Ivan"}
    updateReservation(res)
    fmt.Println(res.Name) // Will print "Ivan" because the original did not change
}

If you need to modify the original, it is better to use a pointer: func updateReservation(r *Reservation).