I understand that Julia doesn’t have “pointers” in the way that C++ does. However, I have stumbled upon an instance in which I feel like I really need something like a pointer that can refer to a variable from within a struct without actually copying that variable’s data into the struct itself. I want to know if there is a better or more Julian way to accomplish this task.
Here is a toy example that illustrates what I am trying to do. Suppose I have written a function that solves linear programs (LPs) in the form \max\lbrace{c^T x : Ax \leq b\rbrace}. The input data (c, A, b) for this function is given by the following struct:
struct LinearProgram
c::Vector{Float64}
A::Matrix{Float64}
b::Vector{Float64}
end
Now, I am interested in what happens to the optimal x when a new constraint is added to this LP, so we have \max\lbrace{c^T x : Ax \leq b, \sum x_i \leq t \rbrace} instead. In particular, I want to vary the value of t and store the associated x-results somewhere. However, I will be doing this for various instances of (c, A, b), so I would like to make sure that each result is paired with the underlying LP data. Therefore, I created the following struct to store my LP results:
struct LinearProgramResult
lp::LinearProgram
t::Float64
x::Vector{Float64}
end
and now my LP solver function looks like this:
function solveparametriclinearprogram(lp::LinearProgram, t::Float64)
# Solve the linear program
# max c⋅x
# s.t. Ax ≤ b
# Σx ≤ t
# and obtain the optimal solution x
return LinearProgramResult(lp, t, x)
end
With this approach, I can store a big list of LinearProgramResult
s without worrying about losing the underlying data. However, because each LinearProgramResult
contains the entire LinearProgram
itself, if I want to try out several values of t for a single LP, then this seems to be a waste of memory.
Therefore, I would like to replace the second line of the LP result struct with a reference to an LP instead, with the understanding that the user modifies the referenced variable at her own risk.
struct LinearProgramResult
lp::pointer(LinearProgram)
t::Float64
x::Vector{Float64}
end
Is this a reasonable thing to want to do? Is there a better approach I should be using instead?