First, Go technically has only pass-by-value. When passing a pointer to an object, you're passing a pointer by value, not passing an object by reference. The difference is subtle but occasionally relevant. For example, you can overwrite the pointer value which has no impact on the caller, as opposed to dereferencing it and overwriting the memory it points to.
// *int means you *must* pass a *int (pointer to int), NOT just an int!
func someFunc(x *int) {
*x = 2 // Whatever variable caller passed in will now be 2
y := 7
x = &y // has no impact on the caller because we overwrote the pointer value!
}
As to your question "Why do we need to have the asterisk in front of the type?": The asterisk indicates that the value is of type pointer to sql.DB
, rather than a value of type sql.DB
. These are not interchangeable!
Why would you want to send a pointer address? So that you can share the value between the caller of a function and the function body, with changes made inside the function reflected in the caller (for example, a pointer is the only way that a "setter" method can work on an object). This is actually what your Java code is doing as well; in Java, you always access objects via references (pointers), so Java does this automatically instead of having you explicitly indicate it. But in Go you can also access an object not via a pointer, so you have to be explicit. If you call a function and pass in an object directly, the function will get a copy of that object, and if the function modifies that object, the caller won't see those changes. So if you want changes to propagate outside the function, you must pass a pointer. That way, the pointer will be copied, but the object that it points to will be shared.
See also: the Go tour section on Pointers, the Go spec section on pointers, the Go spec section on the address operators