djsegal
December 23, 2017, 5:23am
1
Let’s say you have two types of structs:
Users can have many posts. But each post belongs to only one user.
How would you do this in structs?
Some pseudocode:
struct User
posts::AbstractArray{Post}
end
struct Post
author::User
end
The simplest way I could think of is just removing {Post}
from abstract array, but that’s cheating
1 Like
djsegal
December 23, 2017, 5:24am
2
rdeits
December 23, 2017, 6:36am
3
How about:
julia> abstract type AbstractPost end
julia> struct User{V <: Vector{<:AbstractPost}}
posts::V
end
julia> struct Post <: AbstractPost
user::User{Vector{Post}}
end
julia> u1 = User(Post[])
User{Array{Post,1}}(Post[])
julia> p1 = Post(u1)
Post(User{Array{Post,1}}(Post[]))
julia> push!(u1.posts, p1)
1-element Array{Post,1}:
Post(User{Array{Post,1}}(Post[Post(#= circular reference @-3 =#)]))
2 Likes
rdeits
December 23, 2017, 6:48am
4
(note that the AbstractPost
supertype isn’t necessary to make this work, but I think it’s a nice indicator of intent in the absence of being able to write the circular definition you actually want)