Building an array of structs would not suffice, with the generation of new instances done using push! to that array? I do not know if that can be adapted to your problem, but seem much safer than updating a global variable.
If that is not good, I do not see much escaping from what you have done. Except that I perhaps would use a counter that is constant with mutable fields, to avoid messing up with other variables:
julia> struct A
id
x
end
julia> function Generate_A_and_Count!( x, counter )
counter[1] +=1
A(counter[1],x)
end
Generate_A_and_Count (generic function with 1 method)
julia> const A_counter = [0]
julia> A(x) = Generate_A_and_Count!(x,A_counter)
A
julia> A(1.)
A(1, 1.0)
julia> A(1.)
A(2, 1.0)
Probably I should be starting a new thread, but why in the example below A() is available in the global scope, but f() is not?
julia> let
struct A
x
end
A() = A(1)
end
A
julia> A()
A(1)
julia> let
f() = 1
end
(::var"#f#1") (generic function with 1 method)
julia> f()
ERROR: UndefVarError: f not defined
Given that, are let blocks a reasonable choice to define functions (objective functions for optimization solvers, for example), with parameters? Something like:
julia> let
struct f end
a = 1
f(x) = (x-a)^2
end
julia> f(3)
4
Here f is a constructor of the type f (needed for f to be available in the global scope), and a is a constant parameter of the function. Using a struct like that seems ugly, but would that work?
Let blocks create a local scope. Within local scopes when functions are defined Julia makes them local to that scope unless instructed to do otherwise.