I’m writing a program to compute the halftone function, and I need to write a struct to a file because it takes a long time to compute. It consists of an OffsetVector of any real floating-point type. I’ve figured out how to turn any number between 0 and 1, whether Float64 or BigFloat, into a bytestring which I can write to a file, but I need to write the type to the start of the file, so that I can construct the HalftoneApprox when reading it from the file. I could write some elseifs checking whether it’s a Float16, Float32, Float64, or BigFloat, but if someone ever creates the types Float80 (which exists in x86(64)) and Float128 (which exists in POWER), the code will fail. How can I write a type to a file so that I can read it from the file and construct the same type, at least if the architecture has it?
Serialization would help?
You could also print the type and values to a file and then read the contwnts back to a string and parse it to recover the type (and values) with Meta.parse .
If you only want to support types in Base, the lowtech solution is to simply write the type name in the file and reconstruct it with getfield(Base, Symbol(type_name)).
Otherwise you need to look into packages like JLD2 or BSON. The Serialization stdlib can be used but it has a number of caveats when it comes to format stability.
Be aware that most solutions, except the first one, have the potential to execute arbitrary code when parsing the file, which may or may not be a real problem.
To nitpick this needs to be combined with eval, and then also has the potential to execute arbitrary code.
I’ve done this with JLD2.jl and it works pretty well.