I'm trying to reassign a pointer to a new value that's been passed on as func parameter, but once I step out of the function, the pointer has a nil value again.
I've stepped through the code and it seems to work until I step out of the function into the calling function where the passed on pointer still holds a NIL value.
func Prepare(db *sqlx.DB, stmt *sqlx.Stmt, query String) error {
res,err := db.PreparexStatement(context.Background(), query)
stmt = res
return err
}
I would expect the following to work:
func Boot(db *sqlx.DB, stmt *sqlx.Stmt, query String) {
err := Prepare(db, stmt, query)
if err != nil {
//handle
}
}
I'm still fairly new to GO, so I believe I fail to grasp a concept here. Any help would be greatly appreciated.
Parameters act as local variables inside a function. You may change their values, but that only changes the values of the local variables. They are independent from the variables whose value you pass.
If you want to modify something, you have to pass its address, and modify the pointed value, e.g.:
Outputs (try it on the Go Playground):
The same thing applies to pointer variables: if you want to modify a pointer variable, you again have to pass its address, and modify the pointed value. In case of a pointer, the type will be a pointer to pointer, e.g.:
Output (try it on the Go Playground):
Of course if you have a pointer variable and don't want to modify the pointer value just the pointed value, you can just pass the pointer, and modify the pointed value:
Output (try it on the Go Playground):
One thing to note: you can't pass a
nil
pointer to a function and expect to be able to assign anything to the pointed value:nil
pointers point to nowhere. You have to pass a non-nil
pointer, or as an alternative you may return the pointer value (and assign it at the caller).