auto in library functions

Jonathan M Davis jmdavisProg at gmx.com
Sun Dec 23 14:16:02 PST 2012


On Sunday, December 23, 2012 23:05:28 Andrej Mitrovic wrote:
> On 12/23/12, Benjamin Thaut <code at benjamin-thaut.de> wrote:
> > I just created my first pull request for druntime and there where
> > multiple commonets to _not_ use auto. I don't quite understand
> > why it shouldn't be used in library functions. If it should not
> > be used why is it in the language in the first place?
> > 
> > Kind Regards
> > Benjamin Thaut
> 
> auto is mainly useful for complex return types or for nested types
> which you can't otherwise declare (called voldemort types), e.g.:
> 
> auto x = joiner([""], "xyz");
> writeln(typeid(x)); //  => std.algorithm.joiner!(string[],
> string).joiner.Result
> 
> When the type is simple you should use the name of the type instead of
> auto because it serves as useful documentation, especially in library
> functions where you might later have to fix a bug. It's really useful
> to know exactly what type each variable is without having to waste
> time e.g. looking at function declarations to figure out the return
> type.

Yeah. I don't know what they were complaining about in the pull request, but I 
think that Andrej has it right. Basically, when declaring the return type, if 
you need type inference, use auto, but if you don't, then put the explicit 
type so that it's clearer in the documentation. druntime is unlikely to need 
type inference, as its functions generally return simple, explicit types 
rather than depending on the types passed to them like happens often in 
Phobos. And they don't usually return types which are heavily templatized, 
which is where auto return types really shine.

Using auto for local variables, however, is completely differente. There, it's 
frequently best to use it unless you need to declare a variable as a specific 
type (e.g. size_t i = 0; instead of auto i = 0; when you need size_t). It 
makes refactoring the code easier and reduces code breakage when types change. 
But with return types, it affects the documentation and people's ability to 
figure out what a function does, so as useful as auto return types can be, they 
come with a definite cost and should be avoided if they're not needed.

- Jonathan M Davis


More information about the Digitalmars-d mailing list