Repository navigation
Expand file tree
/
Copy pathstruct.zig
More file actions
67 lines (53 loc) · 1.63 KB
/
Copy pathstruct.zig
File metadata and controls
67 lines (53 loc) · 1.63 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
const print = @import("std").debug.print;
const Person = struct {
name: []const u8,
age: u8,
};
const Point = struct {
x: u8,
y: u8,
z: u8,
// varable for struct kinda like static
const num_of_dimensions = 3;
var num: u8 = 0;
fn init(x: u8, y: u8, z: u8) Point {
num += 1;
return Point{ .x = x, .y = y, .z = z };
}
// if first parameter is same as type that called it then its an instance method
fn printPoint(this: Point) void {
print("print: {}\n", .{this});
}
// if you want to modify it you need to make this a pointer
fn increment(this: *Point) void {
this.x += 1;
this.y += 1;
this.z += 1;
}
};
test "struct" {
const alice = Person{ .name = "Diego", .age = 43 };
print("alice: {}\n", .{alice});
const origin: Point = Point{ .x = 0, .y = 0, .z = 0 };
print("origin: {}\n", .{origin});
const origin1: Point = .{ .x = 0, .y = 0, .z = 0 };
print("origin1: {}\n", .{origin1});
print("num_of_dimensions: {}\n", .{Point.num_of_dimensions});
var point3: Point = Point.init(3, 3, 3);
print("point3: {}\n", .{point3});
print("point3.num: {}\n", .{Point.num});
point3.printPoint();
// or you can call it this way
Point.printPoint(point3);
point3.increment();
point3.printPoint();
// tuple is a struct with no name
const tuple = .{ 2, 5.5, true, "hello" };
print("tuple: {}\n", .{tuple});
print("tuple[0]: {}\n", .{tuple[0]});
print("tuple[0]: {}\n", .{tuple.@"0"});
print("tuple len: {}\n", .{tuple.len});
}
pub fn main() void {
print("zig test struct");
}