Best way to make has_many/belongs_to relation for structs?

question

#1

Let’s say you have two types of structs:

  • Users
  • Posts

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


#2

Whoops. Did it again:


#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 =#)]))

Forward declaration of types.
#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)