簡體   English   中英

如何在 Zig 中創建類型化索引

[英]How can I make a typed index in Zig

我有一個算法,它有兩個具有各自索引的數組。 只是,很容易混合兩個索引並訪問具有錯誤索引的數組之一。 例如:

var array1 = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 
var index1 = 7; // the 8th element in array1, fine because array1 has a length of 10
var array2 = [_]u8{ 1, 2, 3, 4, 5 }; 
var index2 = 2; // the 3rd element in array2, fine because array2 has a length of 5
array2[index1] // woops, I used the wrong index with the wrong array

有沒有辦法讓自定義索引類型將數組與特定類型的索引相關聯,這樣使用錯誤類型的索引索引數組會導致編譯錯誤? 如:

var array1 = [_:Index1]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // with index type 'Index1'
var index1 : Index1 = 7; // index of type 'Index1'
var array2 = [_:Index2]u8{ 1, 2, 3, 4, 5 }; // with index type 'Index2'
var index2 : Index2 = 2; // index of type 'Index2'
array2[index1] // ERROR: array2 expects Index2 type index but Index1 type is used
const std = @import("std");


fn PickyArray(comptime T: type, n: usize, extra: anytype) type {
    _ = extra;
    return struct {
        const Self = @This();
        pub const Index = struct {
            idx: usize,
        };
        unsafe_items: [n]T,
        pub fn init(xs: [n]T) Self {
            return .{.unsafe_items = xs};
        }
        pub fn get(self: Self, idx: Index) T {
            return self.unsafe_items[idx.idx];
        }
        pub fn set(self: *Self, idx: Index, v: T) void {
            self.unsafe_items[idx.idx] = v;
        }
        pub fn getPtr(self: Self, idx: Index) *T {
            return &self.unsafe_items[idx.idx];
        }
        pub fn getSlice(self: Self, lo: Index, hi: Index) []T {
            return self.unsafe_items[lo.idx..hi.idx];
        }
    };
}

const Array1 = PickyArray(u8, 10, "Index1");
const Index1 = Array1.Index;
const Array2 = PickyArray(u8, 5, "Index2");
const Index2 = Array2.Index;

pub fn main() void {
    var array1 = Array1.init([_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
    var index1 : Index1 = .{.idx=7}; // index of type 'Index1'
    var array2 = Array2.init([_]u8{ 1, 2, 3, 4, 5 }); // with index type 'Index2'
    var index2 : Index2 = .{.idx=2}; // index of type 'Index2'
    _ = array2.get(index1); // ERROR: array2 expects Index2 type index but Index1 type is used
    _ = array1;
    _ = index1;
    _ = array2;
    _ = index2;
}

對於額外的功勞, getSlice返回的類型不應該是普通切片,並且應該拒絕接受整數索引。

請不要這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM