Slice type coercion

I’m confused with the type coercion around the slice type. Here are examples:

  1. coerce a slice to a many-item pointer. What’s the intention to give up the length property here? E.g.,
const tag_name = @tagName(TestEnum.TestEnumValue);
const ptr_tag_name: [*:0]const u8 = tag_name;

// test/behavior/string_literals.zig file in Zig codebase
  1. comptime slice. Isn’t it runtime-known of the length for a slice? What’s actually a comptime slice?
test "comptime slice" {
    const test_string: []const u8 = "hello";
    try testing.expect(comptimeKnown(test_string));
}

// https://ziggit.dev/t/some-cool-language-tricks/18130#p-80662-h-1-figuring-out-if-a-value-is-comptime-1
pub inline fn comptimeKnown(val: anytype) bool {
    const Tuple = @TypeOf(.{val});
    return @typeInfo(Tuple).@"struct".field_attrs[0].@"comptime";
}
const std = @import("std");
const testing = std.testing;
  1. to save space?
  2. the length of that string is compile-time known. the original type of it is *const [5:0]u8 (immutable pointer to a fixed array) which is coerced to []const u8. the length is still compile-time known
1 Like

So the length of a slice could be runtime-known. Or maybe the documentation should be updated?

The difference between an array and a slice is that the array’s length is part of the type and known at compile-time, whereas the slice’s length is known at runtime.

well, the slice holds a length value that can be changed at runtime. you can put a compile time known value in there and it will still work, and the compiler would know that value at compile time. i don’t think that needs to be mentioned explicitly in the docs.

3 Likes

A slice can be viewed as a struct with two fields: len and ptr. If the two fields of a slice can be determined at compile time and is immutable at run time, then the slice is a comptime slice. For example, the s in the following code is a comptime slice, even if the array it is referencing is a runtime value.

var a: [2]bool = .{true, false}; // a global declaration
const s: []bool = &a;
1 Like
  1. This is roughly the definition of a subtype: every possible value of type A is still valid under the semantics of type B, so it’s okay to coerce from A to B.
    Subtypes allow information loss. E.g., losing mutability information when coercing from *T to *const T. Losing actual alignment information when coercing from *align(64) T to *align(1) T. Losing the actual range of values when coercing from u32 to u64.

But I agree, allowing a coercion from []T to [*]T is a bit far-fetched and unnecessary. slice.ptr feels more explicit and better to me, and I’ve actually never used this coercion, so I wouldn’t mind if it were removed.

  1. Comptime []T is considered equivalent to [N]T, #35328 might help a bit in understanding this. The post I recently discussed about [_]T also happens to mention the use of slices at comptime, which might eventually be used to completely replace the [_]T syntax.
2 Likes