struct Foo
bar
baz
qux
Foo(bar, baz, qux) = (bar+baz) == qux ? error("qux must be the sum of bar and baz") : new(bar, baz, qux)
end
Foo(bar, baz) = Foo(bar, baz, bar+baz)
You can add an outer constructor to do the addition work on construction and use an inner constructor like @Renan_Rabelo suggested to enforce the rule.
You make a good point, @stevengj ! I was just thinking a more verbose error might be helpful to someone trying to make a new instance, depending on the situation.
If I understand your request correctly, a 2-argument outer constructor does what you’ve asked and there’s no need to fiddle with inner constructors. After all, you said you wanted a default value rather than it to always be exactly a particular value (which is where an inner constructor would have been useful).
Thank you for the nice examples which prompted me to try a variation for a slightly different use case.
If I want to generate a structure but with a different type than the structure demands. I can use an outer constructor to do the conversion and generate the structure as follows: