How to change arrays of a mutable struct

Can you post a complete example that produces the error? The following works in Julia 1.6-rc1:

mutable struct Dataset{T<:Real}
    X::AbstractMatrix{T}
    y::AbstractVector{T}
end

function Dataset(
        X::AbstractMatrix{T},
        y::AbstractVector{T}
	) where {T<:Real}
    return Dataset{T}(X, y)
end

function extendDataset(dataset::Dataset, X::AbstractMatrix{T}, y::AbstractVector{T}) where {T <: Real}
	catX = hcat(dataset.X, X)
	caty = vcat(dataset.y, y)
    dataset.X = catX
    dataset.y = caty
    dataset.X = 2 * dataset.X
    dataset.y = 2 * dataset.y
end

julia> d = Dataset([1 2; 3 4], [1,2])
Dataset{Int64}([1 2; 3 4], [1, 2])

julia> extendDataset(d, [4 6]', [3])
3-element Vector{Int64}:
 2
 4
 6

However, why define a Dataset constructor? It seems equivalent to the default constructor. I mean that the following works:

mutable struct Dataset{T<:Real}
    X::AbstractMatrix{T}
    y::AbstractVector{T}
end

julia> Dataset([1 2; 3 4], [1,2])
Dataset{Int64}([1 2; 3 4], [1, 2])

For the function signature I would just write extendDataset(dataset::Dataset, X, y) which has the same performance but is more general (it works for other types, as long as they can be converted).

However I agree with @gustaphe: if you only need to grow your matrix and vector, it’s better to use an immutable struct. A mutable struct might be the right choice if you really need to replace X or y for some reason.

1 Like