Best way to make has_many/belongs_to relation for structs?

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

1 Like

Whoops. Did it again:

https://github.com/JuliaLang/julia/issues/269

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

(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)