Include note about comptime and further elaboration on inferred variable assignment
In Chapter 1, Section 1:
Assignment
Value assignment has the following syntax:
(const|var) identifier[: type] = value.
constindicates thatidentifieris a constant that stores an immutable value.varindicates thatidentifieris a variable that stores a mutable value.: typeis a type annotation foridentifier, and may be omitted if the data type ofvaluecan be inferred.const constant: i32 = 5; // signed 32-bit constant var variable: u32 = 5000; // unsigned 32-bit variable // @as performs an explicit type coercion const inferred_constant = @as(i32, 5); var inferred_variable = @as(u32, 5000);
I think it would be better to elaborate on how type inference works over here by showing all of the methods available to do so. In my limited knowledge of Zig, these are the three methods I know of:
// 1. Explicit coercion (as shown above in your example):
var inferred_variable = @as(u32, 5000);
// 2. Inference from existing variables
var a: i32 = 1;
var b = a + 1; // Inferred as i32
// 3. Using the comptime directive to force a comptime_int
comptime var a = 1;
I think showing the second method out of the three would be the best display of the use of inferred assignment in Zig, and thus should be shown first.
This is also I think a good place to show to the reader early how compile time evaluation works and what comptime_int is in Zig. A short description of both components and a link to the later section about comptime would be sufficient, considering that this tutorial is directed toward people already familiar with a programming language.
Some issues with this:
- 1 and 2 are equivalent; from the perspective of assignment + type inference, they're the same
- 3 is more complicated, in that
varacts ascomptime varwhen in a comptime block
I'm working on restructuring some things at the moment, and I agree a good idea to introduce comptime sooner, but I don't think this is a good solution.
Some issues with this:
- 1 and 2 are equivalent; from the perspective of assignment + type inference, they're the same
I agree that they achieve the same thing here, however my intent was to show the reader that it is possible to write such idioms as presented in method 2. Method 2 may not be as obvious to the reader if only method 1 is presented to them. Also, I don't think a user is likely to use explicit coercion everytime inferrred assignment is used, thus rendering method 1 an illustration of a valid use, but a bit useless. Illustration both method 1 and 2 would be a good idea imo.
- 3 is more complicated, in that
varacts ascomptime varwhen in a comptime blockI'm working on restructuring some things at the moment, and I agree a good idea to introduce comptime sooner, but I don't think this is a good solution.
Yes, I agree that a better approach than what I suggested for this would be a more suitable solution.