Repository navigation
Expand file tree
/
Copy pathfunctions.zig
More file actions
99 lines (82 loc) · 2.09 KB
/
Copy pathfunctions.zig
File metadata and controls
99 lines (82 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//! this is a top level comment comment
//!
//!
const std = @import("std");
const hellow = @import("./import_func.zig").hellow;
const expect = @import("std").testing.expect;
const print = std.debug.print;
/// this is a document comment: public functions can be exported and used by other files
pub fn addNumbers(num1: u8, num2: u8) u16 {
return num1 + num2;
}
fn greet() void {
print("greeting\n", .{});
}
fn greet_name(name: []const u8) void {
print("greet: {s}\n", .{name});
}
inline fn square(x: i32) i32 {
return x * x;
}
fn divide(a: i32, b: i32) !i32 {
if (b == 0) {
return error.DivisionByZero;
}
return @divExact(a, b);
}
const GreatArgs = struct {
name: []const u8,
age: u32 = 0,
};
fn greet_args(args: GreatArgs) void {
if (args.age != 0) {
print("name: {s}, age: {}\n", .{ args.name, args.age });
} else {
print("name: {s}\n", .{args.name});
}
}
fn applyOperation(a: u8, b: u8, operation: fn (u8, u8) u16) i32 {
return operation(a, b);
}
const multiply = struct {
fn call(a: i32, b: i32) i32 {
return a * b;
}
};
test "test functions" {
const resAddNumbers = addNumbers(2, 3);
print("resAddNumbers: {}\n", .{resAddNumbers});
greet();
greet_name("Diego");
const resSquare = square(2);
print("resSquare: {}\n", .{resSquare});
const value = divide(10, 2);
if (value) |val| {
print("value: {}\n", .{val});
} else |err| {
print("err: {}\n", .{err});
}
greet_args(.{ .name = "Diego", .age = 43 });
greet_args(.{ .name = "Andy" });
const applyRes = applyOperation(2, 3, addNumbers);
print("applyRes: {}\n", .{applyRes});
const res3 = multiply.call(3, 2);
print("res3: {}\n", .{res3});
hellow();
}
fn addFive(x: u32) u32 {
return x + 5;
}
test "function 1" {
const y = addFive(0);
try expect(@TypeOf(y) == u32);
try expect(y == 5);
}
fn fibonacci(n: u16) u16 {
if (n == 0 or n == 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
test "function recursion" {
const x = fibonacci(10);
try expect(x == 55);
}