1. Write a program that computes several Fibonacci numbers with comptime. Print the results at runtime.
Write a program that computes several Fibonacci numbers with
comptime. Print the results at runtime.Rewrite this declaration so the value is computed during compilation:
const x = 10 * 20;- Explain why this code is invalid:
var n: usize = 4;
const a = comptime n * 2;- Write a function:
fn square(x: i32) i32Call it both at runtime and with comptime.
- Write a generic function:
fn zero(comptime T: type) TReturn the zero value of the given type.
- Write a generic function:
fn max(comptime T: type, a: T, b: T) TTest it with integers and floating-point values.
- Write a function:
fn Array(comptime T: type, comptime N: usize) typeReturn the type [N]T.
- Write a function:
fn Pair(comptime T: type) typeReturn a struct with fields first and second.
Add methods
swapandprintto the type returned byPair.Write a function:
fn Buffer(comptime N: usize) typeThe returned type should contain:
data: [N]u8
len: usizeAdd methods
appendandcleartoBuffer.Write a function:
fn isInteger(comptime T: type) boolUse @typeInfo.
- Write a function:
fn isFloat(comptime T: type) boolUse @typeInfo.
- Write a function that prints the names and sizes of these types:
u8
u16
u32
u64Use inline for.
- Write an inline loop over this tuple:
.{ 10, true, "zig" }Print each value with {any}.
- Write a function:
fn fieldCount(comptime T: type) usizeReturn the number of fields in a struct.
- Write a function:
fn printFields(comptime T: type) voidPrint all field names and field types in a struct.
- Write a function:
fn enumTagCount(comptime T: type) usizeReturn the number of tags in an enum.
- Write a function:
fn printEnumTags(comptime T: type) voidPrint all enum tag names.
- Write a compile-time check that rejects systems where:
@sizeOf(usize) < 8- Write a generic stack type:
fn Stack(comptime T: type, comptime N: usize) typeImplement:
pushpoppeekclear
Modify
Stackso it reports overflow with an error.Write a type generator:
fn Matrix(comptime T: type, comptime rows: usize, comptime cols: usize) typeStore values in:
[rows][cols]T- Write a generic function:
fn swap(comptime T: type, a: *T, b: *T) void- Write a function:
fn hasField(comptime T: type, comptime name: []const u8) boolReturn whether a struct contains the named field.
Write a compile-time assertion that requires a struct to contain a field named
id.Write a function:
fn describe(comptime T: type) voidPrint whether the type is an integer, float, pointer, struct, enum, or union.
Write a type generator that returns one struct when a compile-time boolean is true and another when it is false.
Explain the difference between:
forand:
inline for- Explain why Zig uses ordinary functions for generic programming instead of a separate template language.