Auto keyword and when to use it
Jim Balter
Jim at Balter.name
Tue Aug 21 18:44:15 UTC 2018
On Tuesday, 21 August 2018 at 18:18:25 UTC, QueenSvetlana wrote:
> On Tuesday, 21 August 2018 at 16:15:32 UTC, XavierAP wrote:
>>Only if someone
>> likes "Type x = new Type()" instead of "auto x = new Type()" I
>> would say they're clearly wrong.
>
> As you stated it's up to the programmer to decided. I'm in
> favor of Type x = new Type()
There is nothing to recommend such redundancy; don't do it.
> because when it comes to constructing a class it usually means
> more code to verify the types
Type inference doesn't require more code.
> for example:
Your example has no bearing on any of the above ... it's not an
example of it.
>
> class Person {
> auto firstName;
> auto lastName;
>
> // constuctor to set first and last names
>
> }
That code is meaningless and isn't legal. You need to either
provide explicit types, or they need to be inferable from the
type of the initializer.
> The compiler doesn't know know what firstName or lastName is
> supposed to be and a programmer might make the obvious
> assumption and use them as strings.
The programmer can't make any assumption because the code is not
remotely legal.
> Doing this also means you have reject any type that isn't a
> string which means a private function to check the type that
> was pass to the constructor before initializing it. Where as if
> you declared it as a string to start of with, all you have to
> ensure is that it's not blank or contain illegal characters.
This is all incoherent. D is a statically typed language.
> As the answer stated above doing what I showed in my example
> isn't allowed and this is where Python gets frustrating,
> because at any point the types could change. They introduced
> type hints, but it's not enforced, it just makes it more
> readable, you still have to write code to ensure the proper
> types were passed.
Python is not statically typed; D is. Why are you talking about
Python? You asked whether D's auto is like C#'s var ... it is,
but it doesn't have C#'s pointless restriction of not being
allowed for non-local declarations.
More information about the Digitalmars-d-learn
mailing list