Why cannot the starting index of the range of the slice be omitted?

Here is the Python code to print part of a string:

s = "Hello, Zig!"
print(s[7:10]) # "Zig"
print(s[7:]) # "Zig!"
print(s[:5]) # "Hello"

Next, I wrote a Zig’s code that does the same thing as the code above:

const s = "Hello, Zig!";
const stdout = std.io.getStdOut().writer();
try stdout.print("{s}\n", .{s[7..10]}); // "Zig"
try stdout.print("{s}\n", .{s[7..]}); // "Zig!"
try stdout.print("{s}\n", .{s[..5]}); // "Hello"

This is actually incorrect because the last line is an invalid code.

When I first learned Zig, I thought that s[0..5] could be written as s[..5].

This is for the following reasons:

  • Because s[7..] is a valid code.
  • Because code like s[..5] is often valid in other languages (e.g., s[:5] in Python).

Why cannot s[0..5] be written as s[..5] in Zig? I tried to find out why this is, but I couldn’t find an answer.

1 Like

Hmm I think one reason might be:

  • Only one obvious way to do things.

If there was s[0..5] and s[..5] there would be two different ways to do the same thing.

s[7..] is the only way to slice starting from 7 without explicitly providing the end, because the end is different based on the length of s.

For s[..5] there only ever could be 0 as start, so I think the reasoning may be, that when there is only one case, it is best to make it explicit.

Which helps with

  • Favor reading code over writing code.

Also if you could elide the start and the end you would get this awkward corner case:
s[..]

I mostly would say that, it not needing to be optional, to implement the feature (having a start index), makes the syntax have less variance and I think that may be the primary reason, why it is like it is.

With s[3..] you can’t implement it, except if you remove the feature entirely and require people to write s[3..s.len] instead.

But if you want some more official reason, you may have to dig through a bunch of issues or the source code, where and when the syntax was implemented.
This is just me speculating.

5 Likes

Amusingly, that’s valid Python code :smiley: (OK, s[:], but the same concept nonetheless)