@@ -6,28 +6,13 @@ const Point = struct {
6
6
y : f32 ,
7
7
};
8
8
9
- // Maybe we want to pass it to OpenGL so we want to be particular about
10
- // how the bytes are arranged.
11
- const Point2 = packed struct {
12
- x : f32 ,
13
- y : f32 ,
14
- };
15
-
16
9
// Declare an instance of a struct.
17
- const p = Point {
10
+ const p : Point = . {
18
11
.x = 0.12 ,
19
12
.y = 0.34 ,
20
13
};
21
14
22
- // Maybe we're not ready to fill out some of the fields.
23
- var p2 = Point {
24
- .x = 0.12 ,
25
- .y = undefined ,
26
- };
27
-
28
- // Structs can have methods
29
- // Struct methods are not special, they are only namespaced
30
- // functions that you can call with dot syntax.
15
+ // Functions in the struct's namespace can be called with dot syntax.
31
16
const Vec3 = struct {
32
17
x : f32 ,
33
18
y : f32 ,
@@ -46,7 +31,6 @@ const Vec3 = struct {
46
31
}
47
32
};
48
33
49
- const expect = @import ("std" ).testing .expect ;
50
34
test "dot product" {
51
35
const v1 = Vec3 .init (1.0 , 0.0 , 0.0 );
52
36
const v2 = Vec3 .init (0.0 , 1.0 , 0.0 );
@@ -67,14 +51,14 @@ test "struct namespaced variable" {
67
51
try expect (Empty .PI == 3.14 );
68
52
try expect (@sizeOf (Empty ) == 0 );
69
53
70
- // you can still instantiate an empty struct
71
- const does_nothing = Empty {};
54
+ // Empty structs can be instantiated the same as usual.
55
+ const does_nothing : Empty = . {};
72
56
73
57
_ = does_nothing ;
74
58
}
75
59
76
- // struct field order is determined by the compiler for optimal performance.
77
- // however, you can still calculate a struct base pointer given a field pointer:
60
+ // Struct field order is determined by the compiler, however, a base pointer
61
+ // can be computed from a field pointer:
78
62
fn setYBasedOnX (x : * f32 , y : f32 ) void {
79
63
const point : * Point = @fieldParentPtr ("x" , x );
80
64
point .y = y ;
@@ -88,8 +72,7 @@ test "field parent pointer" {
88
72
try expect (point .y == 0.9 );
89
73
}
90
74
91
- // You can return a struct from a function. This is how we do generics
92
- // in Zig:
75
+ // Structs can be returned from functions.
93
76
fn LinkedList (comptime T : type ) type {
94
77
return struct {
95
78
pub const Node = struct {
@@ -105,8 +88,7 @@ fn LinkedList(comptime T: type) type {
105
88
}
106
89
107
90
test "linked list" {
108
- // Functions called at compile-time are memoized. This means you can
109
- // do this:
91
+ // Functions called at compile-time are memoized.
110
92
try expect (LinkedList (i32 ) == LinkedList (i32 ));
111
93
112
94
const list = LinkedList (i32 ){
@@ -139,4 +121,6 @@ test "linked list" {
139
121
// instead of try expect(list2.first.?.*.data == 1234);
140
122
}
141
123
124
+ const expect = @import ("std" ).testing .expect ;
125
+
142
126
// test
0 commit comments