YouTip LogoYouTip

Zig Array Slice

In the Zig programming language, arrays and slices are basic structures used to store and manipulate a set of data of the same type. * **Array**: Used to store a fixed-size set of data of the same type, with the size specified at definition, stored on the stack. * **Slice**: Used to reference a portion of an array or other contiguous memory area, with dynamically adjustable size, more flexible, typically references heap memory. **Array:** * An array is a fixed-length sequence whose size is determined at compile time. * The type of an array is ``, where `T` is the type of elements in the array. * The memory of an array is contiguous, which gives them a performance advantage, especially when processing large amounts of data. **Slice:** * A slice is a dynamic-length sequence that allows its size to be changed at runtime. * The type of a slice is `[]T`, where `T` is the type of elements in the slice. * A slice is actually a reference to an array, containing a pointer to the array and the length of the slice. * Slices can handle data more flexibly as they can easily be shared and passed between different arrays. * * * ## Array Arrays are of fixed size, stored on the stack, and all elements must be of the same type. You can use the `[]` syntax to define an array and specify its size. The array type is defined as `[T; N]`, where T is the type of array elements and N is the length of the array. Array elements can be accessed by index, with indices starting from 0. ### Syntax Format const arrayName: ElementType = ElementType{element1, element2, ...}; **Parameter Description:** * `arrayName`: The name of the array. * `size`: The size of the array (number of elements), which is a compile-time constant. * `ElementType`: The type of elements in the array. * `element1, element2, ...`: The elements in the array. An array is a fixed-size contiguous memory block whose size is determined at compile time: var myArray: u8 = u8{0} ** 10; // Define and initialize a u8 type array of size 10 ## Example const std = @import("std"); pub fn main()void{ // Define an array containing 5 i32 type elements const arr:i32 =i32{1, 2, 3, 4, 5}; // Access array elements by index std.debug.print("First element: {}n", .{arr}); std.debug.print("Third element: {}n", .{arr}); // The size of the array is fixed const size: usize = arr.len; std.debug.print("Array size: {}n", .{size}); } The compilation output is: First element: 1Third element: 3Array size: 5 ### Traversing Arrays You can use a for loop to traverse the elements of an array. ## Example const std = @import("std"); pub fn main()void{ const arr:i32 =i32{1, 2, 3, 4, 5}; var index: usize =0; // Traverse the array for(arr)|item|{ std.debug.print("Index: {}, Item: {}n", .{ index, item }); index +=1; } } The compilation output is: Index: 0, Item: 1Index: 1, Item: 2Index: 2, Item: 3Index: 3, Item: 4Index: 4, Item: 5 * * * ## Slice A slice is a reference to a portion of an array or other contiguous memory area. Slices can dynamically adjust their size and are more flexible than arrays, but their elements are stored on the heap. ### Definition and Initialization A slice is a reference to a portion of an array or other contiguous memory area. Slices are dynamic and can change their size, typically used to represent a portion of an array or dynamically allocated memory blocks. ### Syntax Format const sliceName: []ElementType = array[start..end]; **Parameter Description:** * `sliceName`: The name of the slice. * `ElementType`: The type of elements in the slice. * `array[start..end]`: Extract a sub-slice from `array`, where `start` and `end` are indices. Slices can be created from a subset of an array, or from a pointer and length: var myArray: u8 = ...; // Assume already initializedvar mySlice = myArray[2..7]; // Create a slice containing elements at indices 2 to 6// Or use pointer and lengthvar mySlicePtr = myArray[2..]; // Create a slice starting from index 2 to the end of the array Slices provide some built-in methods to manipulate slices, such as: * `len`: Get the length of the slice. * `ptr`: Get the pointer of the slice. * `capacity`: Get the capacity of the slice, which is the maximum length of the array portion it can reference. ## Example const std = @import("std"); pub fn main()void{ var arr:i32 =i32{1, 2, 3, 4, 5}; // Create a slice from the array const slice:[]i32 = arr[1..4]; // Access slice elements by index std.debug.print("First element of slice: {}n", .{slice}); std.debug.print("Second element of slice: {}n", .{slice}); // The length of the slice const length: usize = slice.len; std.debug.print("Slice length: {}n", .{length}); } The compilation output is: First element of slice: 2Second element of slice: 3Slice length: 3 ### Traversing Slices Similar to arrays, you can use a for loop to traverse slices. ## Example const std = @import("std"); pub fn main()void{ var arr:i32 =i32{1, 2, 3, 4, 5}; const slice:[]i32 = arr[1..4]; var index: usize =1; // Traverse the slice for(slice)|item|{ std.debug.print("Index: {}, Item: {}n", .{ index, item }); index +=1; } } The compilation output is: Index: 1, Item: 2Index: 2, Item: 3Index: 3, Item: 4 * * * ## Differences Between Arrays and Slices * **Size**: The size of an array is fixed and determined at definition; the size of a slice can be dynamically adjusted. * **Storage Location**: Arrays are typically stored on the stack, while the memory referenced by slices can be on the heap. * **Flexibility**: Slices are more flexible and can reference a portion of an array or dynamically allocated memory. | Feature | Array | Slice | | --- | --- | --- | | Size | Fixed, determined at compile time | Dynamic, can change size | | Element Type | Same | Same | | Memory Location | Usually on the stack (local variables) | Referenced memory may be on heap or stack | | Access | By index | By start and end indices of the slice | | Creation | Direct definition | Created from arrays or other slices | In the following example, the printArray function accepts a fixed-size array as a parameter, while the printSlice function accepts a slice as a parameter. Through these functions, you can see the
← Git AdvanceCss Sel Has β†’