carbon-lang icon indicating copy to clipboard operation
carbon-lang copied to clipboard

Syntax for variable assignment is ambiguous

Open ahives opened this issue 3 years ago • 1 comments

If I wanted to declare and assign variables in most languages including C++ it is pretty straightforward. I would do something like this:

float area = 0;

The language implicitly understands that I am declaring a variable, area, of type float and assigning it a value of 0. However, in Carbon this same code would be written as:

var area: f32 = 0;

What is wrong with this? Well, in most modern languages the keyword var has become synonymous with “duck typing” (e.g., C#, JavaScript, etc.). In other words, the compiler will figure out the type based on its usage. To a Carbon newbie the above syntax reads as follows, “Carbon, please declare a variable named area and you figure out the type…wait. I mean, the variable area should be a 32 bit float and initialize it to 0.” That is overly complicated for such a simple concept.

In C# for example, it allows for both static and dynamic typing. I could write the above Carbon code as follows:

var area = 0.0F;

…or I could write it as:

float area = 0.0F;

I can declare the variable in such a way that leaves it up to the compiler to determine the type (i.e. duck typing) or I can be more explicit. I suggest the following syntax for declaring variables in Carbon:

f32 area = 0;

Why? If I am not mistaken, the idea is to make moving from other languages (e.g., C++) as frictionless as possible. Assuming that is the goal, removing the ambiguity that I have outlined in this issue would be a step in the right direction.

ahives avatar Jul 30 '22 20:07 ahives

This seems to be the var equivalent of #1578.

Just to note, I think this doesn't introduce any new information as compared to the discussion and alternatives in https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p0339.md. Other var naming options and not having var were considered. However, since we haven't discussed this since the growth in audience, I'll leave this for leads.

jonmeow avatar Jul 30 '22 21:07 jonmeow

I think this is the alternative discussed in p0851: allow eliding the : type portion of a variable declaration. The concern being raised in this issue is the cross-language inconsistency argument that p0851 discusses, which we already took into account when reaching the current design. Please refer to that proposal to see why we chose this syntax despite that concern.

Given that we've already considered this option and the rationale for it, I don't think there's a new decision to be made here, so closing. Please reopen if you think there's a concern that we've not previously considered based on the writeup in p0851.

zygoloid avatar Aug 01 '22 21:08 zygoloid