On Tuesday, October 11, 2016 07:55:36 orip via Digitalmars-d-learn wrote: > I get "Error: mismatched function return type inference" errors > with choosing the return type for functions that work on ranges > using, e.g, std.algorithm or std.range functions, but have > different behavior based on runtime values. The return type is > always a range with the same underlying type. > > Here's an example: > > auto foo(int[] ints) { > import std.range; > if (ints.length > 10) { > return chain(ints[0..5], ints[8..$]); > } else { > //return ints; // Error: mismatched function return type > inference of int[] and Result > return chain(ints[0..0], ints[0..$]); // This workaround > compiles > } > } > > Is there a compatible return type that can be used, or some other > workaround? > I couldn't find one when searching for the error or looking at > the phobos source code. > > Thanks! orip
You're workaround is basically doing what you need to do. A function can only return one type. The fact that both return statements are returning ranges over the same kind of elements is irrelevant. They have to be _exactly_ the same type. So, either you need to convert the range for the first return statement into int[] so that it matches the second (e.g. by calling array on the result or just using ~), or you need to call chain on two int[]s for the second return statement so that it matches the first. The second option (which your workaround does) is better if you don't intend to convert the result to an array, since it avoids allocating an array, but if you're just going to convert the result to int[] anyway, the first option would be better. Regardless, you can't have a function returning different types from different return statements - even with auto. The compiler needs to know exactly what the return type is whether you type it or not; auto just infers it for you rather than requiring you to type it out. - Jonathan M Davis