returning different types via function
bearophile
bearophileHUGS at lycos.com
Tue Nov 19 11:31:39 PST 2013
seany:
> I have a function FUNC, it takes a string array, and does
> something with it, and retruns the same. Implemented based on a
> previous thread, here is what i have
>
> string[] FUNC (ref string[] ZZ)
I told you to use ref if you want to modify in-place the length
of the array, as in the exaple you have shown. In general you
don't need the ref.
> Now, I want, should the function be not successful in doing
> what it intends to do, to return a boolean value of false, to
> ZZ, un fortunately ZZ is already a string[] (so i want liek a C
> style fopen -like function, that , although called with the
> syntax: file *f = fopen(balh, "bla"); can set f to be false)
>
> Is this possible in D?
The clean design is to use std.typecons.Nullable:
Nullable!(string[]) func(string[] zz) {
Also consider making zz const (with "in"), and creating a
pure/nothrow function:
Nullable!(string[]) func(in string[] zz) pure nothrow {
A less clean but sometimes acceptable design is to use a "out"
variable in func, and return a boolean:
bool func(string[] zz, out string[] result) {
--------------------
Dicebot:
> You can wrap return type in Variant
> (http://dlang.org/phobos/std_variant.html) but it is
> inefficient, weakens typing and considered a bad approach in
> natively compiled language. Better approach probably is to use
> null as an indicator (as string[] is a reference type) or throw
> an exception.
A Nullable in usually efficient enough (there is even an
alternative Nullable that doesn't increase the data size), it
makes typing stronger, and it should become more common in system
languages (and indeed it's commonly used in Rust, where the
pattern matching makes its usage nicer). [] is a bad indicator
because perhaps ZZ could be empty, so you are mixing signals.
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list