I am seeing strange behavior in NLsolve package. Mutating function is not working

I am trying to optimize a function that has several contributions. So I need to add several terms to it, but when I pass that function to nlsolve I am getting strange results. I have reproduced a minimal example that reproduces the problem.

using SparseArrays
using NLsolve
bins = Int(4)

function f!(f0,x)
    f0=0*x
    for i in 1:bins
        f0[i] = f0[i] + x[i]*x[i] - 1
    end
end

function j!(j0,x)
    for i in 1:bins
        j0[i,i] = 2.0*x[i]
    end
end


x0 = 0.5*ones(bins)
f0 = zeros(Float64,bins)
f!(f0,x0)
j0 = spzeros(bins, bins)
j!(j0,x0)
df = OnceDifferentiable(f!, j!, x0, f0, j0)

sol = nlsolve(df, x0,method=:newton)
println(sol)

If I run this code I get the answer [0.5,0.5,0.5,0.5], which is obviously wrong. But if I change the function f! to

function f!(f0,x)
    for i in 1:bins
        f0[i] = x[i]*x[i] - 1
    end
end

then I get the correct result. If I want to optimize a function that has several components it is easier to initialize f0 to zero and add components to it. But that does not work with NLsolve. Is there a way to initialize f0 to zero and add various components to it? Also, this behavior is quite nonintuitive. Functions should not behave this way depending on the sequence of mutation.

This assigns the name f0 to a new value 0*x so the value you are intended to mutate is no longer accessible. Try

f0[:] = 0*x

Thanks a lot! That works.