Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structs duplication in Julia

Tags:

struct

julia

I have package called sandwich, it then has:

A file flavours.jl which defines a struct HamCheeseSandwich.

The file factory.jl is a module which first first runs include("flavours.jl") and has a method make_sandwich which creates a HamCheeseSandwich, except rather than producing a HamCheeseSandwich it returns sandwich.factory.HamCheeseSandwich

The last file is printer.jl , here the sandwich made in factory.jl fails with MethodError: no method matching print_sandwich(::sandwich.factory.HamCheeseSandwich)

# printer.jl
function print_sandwich(sandwich::HamCheeseSandwich)
    println("Enjoy your sandwich")
    println(sandwich)
end

When I check the types

Julia> sandwich.factory.HamCheeseSandwich == HamCheeseSandwich
false

Which suggests the problem is my use of include has created two versions of HamCheeseSandwich.

To reproduce

A working example can be seen at this repo:https://github.com/this-josh/Julia-structs-question

This behaviour can be reproduced with

using sandwich
s = factory.make_sandwich(true,false)
print_sandwich(s)

My question is how should I use includes within my package to prevent the duplication of HamCheeseSandwich and to make sure I can still type hint as in printer.jl

like image 337
this_josh Avatar asked Oct 24 '25 01:10

this_josh


1 Answers

You are defining the type HamSandwich several times and you should do it once and then reference the definition.

Hence your code should be:

module Sandwich
  module Flavours
    struct HamSandwich end
  end
  module Factory
     import ..Flavours
     makeSandwich() = Flavours.HamSandwich()
  end 
end

Testing:

julia> using Main.Sandwich

julia> Sandwich.Factory.makeSandwich()
Main.Sandwich.Flavours.HamSandwich()
like image 184
Przemyslaw Szufel Avatar answered Oct 27 '25 02:10

Przemyslaw Szufel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!