├── LICENSE ├── README.md └── interfaces.zig /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Interface idioms/patterns in zig standard libraries ## 2 | 3 | ### introduction ### 4 | In zig, you can declare functions in struct, enum, union and opaque. Functions whose 1st argument has type of its containing struct/enum/union/opaque are methods which can be invoked through dot syntax. Java and Go support "interface" for creating abstractions with a group of methods (or method-set). Normally interfaces hold so-called vtable for dynamic dispatching. Although zig doesn't support interface as a language feature yet, its standard libraries apply a few code idioms or patterns to achieve similar effects. 5 | 6 | Similar to other languages, zig code idiom and patterns enable: 7 | * type checking instance/object methods against interface types at compile time, 8 | * dynamic dispatching at runtime. 9 | 10 | There are some notable differences: 11 | * Go's interfaces are independent from the types/instances they abstract over. Interfaces can be added at any time when common patterns of api/methods are observed across diverse types. There is no need going back to change types for implementing new interfaces, that is required for Java. 12 | * Go's interfaces contain only vtab for dynamic dispatching and small method-set/vtable are preferred, eg. io.Reader and io.Writer with single method. Common utilities such as io.Copy, CopyN, ReadFull, ReadAtLeast are provided as package functions using those small interfaces. Zig's interfaces, such as std.mem.Allocator, typically contains both vtable and common utilities as methods; so they normally have many methods. 13 | 14 | The following are study notes of zig's code idioms/patterns for dynamic dispatching, with code extracts from zig standard libraries. To focus on vtab/dynamic dispatching, utility methods are removed and code are modified a bit to fit Go's model of small interfaces independent from concrete types. 15 | 16 | Full code is located in this [repo](https://github.com/yglcode/zig_interfaces) and you can run it with "zig test interfaces.zig". 17 | 18 | ### set up ### 19 | Let's use the classical OOP example, create a few shapes: Point, Box and Circle. 20 | 21 | ```zig 22 | const Point = struct { 23 | x: i32 = 0, 24 | y: i32 = 0, 25 | pub fn move(self: *Point, dx: i32, dy: i32) void { 26 | self.x += dx; 27 | self.y += dy; 28 | } 29 | pub fn draw(self: *Point) void { 30 | print("point@<{d},{d}>\n", .{ self.x, self.y }); 31 | } 32 | }; 33 | 34 | const Box = struct { 35 | p1: Point, 36 | p2: Point, 37 | pub fn init(p1: Point, p2: Point) Box { 38 | return .{ .p1 = p1, .p2 = p2 }; 39 | } 40 | pub fn move(self: *Box, dx: i32, dy: i32) void { 41 | ...... 42 | } 43 | pub fn draw(self: *Box) void { 44 | ...... 45 | } 46 | }; 47 | 48 | const Circle = struct { 49 | center: Point, 50 | radius: i32, 51 | pub fn init(c: Point, r: i32) Circle { 52 | return .{ .center = c, .radius = r }; 53 | } 54 | pub fn move(self: *Circle, dx: i32, dy: i32) void { 55 | self.center.move(dx, dy); 56 | } 57 | pub fn draw(self: *Circle) void { 58 | ...... 59 | } 60 | }; 61 | 62 | //create a set of "shapes" for test 63 | fn init_data() struct { point: Point, box: Box, circle: Circle } { 64 | return .{ 65 | .point = Point{}, 66 | .box = Box.init(Point{}, Point{ .x = 2, .y = 3 }), 67 | .circle = Circle.init(Point{}, 5), 68 | }; 69 | } 70 | ``` 71 | ### interface 1: enum tagged union ### 72 | Using enum tagged union for interfaces is introduced by Loris Cro ["Easy Interfaces with zig 0.10.0"](https://zig.news/kristoff/easy-interfaces-with-zig-0100-2hc5). This is the simplest solution, although you have to explicitly list, in the union, all the variant types which "implement" the interface. 73 | ``` zig 74 | const Shape1 = union(enum) { 75 | point: *Point, 76 | box: *Box, 77 | circle: *Circle, 78 | pub fn move(self: Shape1, dx: i32, dy: i32) void { 79 | switch (self) { 80 | inline else => |s| s.move(dx, dy), 81 | } 82 | } 83 | pub fn draw(self: Shape1) void { 84 | switch (self) { 85 | inline else => |s| s.draw(), 86 | } 87 | } 88 | }; 89 | ``` 90 | We can test it as following: 91 | 92 | ``` zig 93 | test "union_as_intf" { 94 | var data = init_data(); 95 | var shapes = [_]Shape1{ 96 | .{ .point = &data.point }, 97 | .{ .box = &data.box }, 98 | .{ .circle = &data.circle }, 99 | }; 100 | for (shapes) |s| { 101 | s.move(11, 22); 102 | s.draw(); 103 | } 104 | } 105 | ``` 106 | ### interface 2: 1st implementation of vtable and dynamic disptaching ### 107 | Zig has switched from old style dynamic dispatching based on embedded vtab and #fieldParentPtr(), to the following pattern based on "fat pointer" interface; please go to this article for more details ["Allocgate is coming in Zig 0.9,..."](https://pithlessly.github.io/allocgate.html). 108 | 109 | Interface std.mem.Allocator uses this pattern, and all standard allocators, std.heap.[ArenaAllocator, GeneralPurposeAllocator, ...] have a method "allocator() Allocator" to expose this interface. The following code changed a bit to douple the interface from implementations. 110 | 111 | ``` zig 112 | const Shape2 = struct { 113 | // define interface fields: ptr,vtab 114 | ptr: *anyopaque, //ptr to instance 115 | vtab: *const VTab, //ptr to vtab 116 | const VTab = struct { 117 | draw: *const fn (ptr: *anyopaque) void, 118 | move: *const fn (ptr: *anyopaque, dx: i32, dy: i32) void, 119 | }; 120 | 121 | // define interface methods wrapping vtable calls 122 | pub fn draw(self: Shape2) void { 123 | self.vtab.draw(self.ptr); 124 | } 125 | pub fn move(self: Shape2, dx: i32, dy: i32) void { 126 | self.vtab.move(self.ptr, dx, dy); 127 | } 128 | 129 | // cast concrete implementation types/objs to interface 130 | pub fn init(obj: anytype) Shape2 { 131 | const Ptr = @TypeOf(obj); 132 | const PtrInfo = @typeInfo(Ptr); 133 | assert(PtrInfo == .Pointer); // Must be a pointer 134 | assert(PtrInfo.Pointer.size == .One); // Must be a single-item pointer 135 | assert(@typeInfo(PtrInfo.Pointer.child) == .Struct); // Must point to a struct 136 | const alignment = PtrInfo.Pointer.alignment; 137 | const impl = struct { 138 | fn draw(ptr: *anyopaque) void { 139 | const self = @ptrCast(Ptr, @alignCast(alignment, ptr)); 140 | self.draw(); 141 | } 142 | fn move(ptr: *anyopaque, dx: i32, dy: i32) void { 143 | const self = @ptrCast(Ptr, @alignCast(alignment, ptr)); 144 | self.move(dx, dy); 145 | } 146 | }; 147 | return .{ 148 | .ptr = obj, 149 | .vtab = &.{ 150 | .draw = impl.draw, 151 | .move = impl.move, 152 | }, 153 | }; 154 | } 155 | }; 156 | ``` 157 | We can test it as following: 158 | 159 | ``` zig 160 | test "vtab1_as_intf" { 161 | var data = init_data(); 162 | var shapes = [_]Shape2{ 163 | Shape2.init(&data.point), 164 | Shape2.init(&data.box), 165 | Shape2.init(&data.circle), 166 | }; 167 | for (shapes) |s| { 168 | s.move(11, 22); 169 | s.draw(); 170 | } 171 | } 172 | ``` 173 | ### interface 3: 2nd implementation of vtab and dynamic dispatch ### 174 | In above 1st implementation, when "casting" a Box into interface Shape2 thru Shape2.init(), the box instance is type-checked for implementing the methods of Shape2 (matching signatures including names). There are two changes in the 2nd implementation: 175 | * the vtable is inlined in the interface struct (possible minus point, interface size increased). 176 | * methods to be type checked against interface are explicitly passed in as function pointers, that possiblely enable the use case of passing in different methods, as long as they have same arguments/return types. For examples, if Box has extra methods, stopAt(i32,i32) or even scale(i32,i32), we can pass them in place of move(). 177 | 178 | Interface std.rand.Random and all std.rand.[Pcg, Sfc64, ...] use this pattern. 179 | ``` zig 180 | const Shape3 = struct { 181 | // define interface fields: ptr,vtab 182 | // ptr to instance 183 | ptr: *anyopaque, 184 | // inline vtable 185 | drawFnPtr: *const fn (ptr: *anyopaque) void, 186 | moveFnPtr: *const fn (ptr: *anyopaque, dx: i32, dy: i32) void, 187 | 188 | pub fn init( 189 | obj: anytype, 190 | comptime drawFn: fn (ptr: @TypeOf(obj)) void, 191 | comptime moveFn: fn (ptr: @TypeOf(obj), dx: i32, dy: i32) void, 192 | ) Shape3 { 193 | const Ptr = @TypeOf(obj); 194 | assert(@typeInfo(Ptr) == .Pointer); // Must be a pointer 195 | assert(@typeInfo(Ptr).Pointer.size == .One); // Must be a single-item pointer 196 | assert(@typeInfo(@typeInfo(Ptr).Pointer.child) == .Struct); // Must point to a struct 197 | const alignment = @typeInfo(Ptr).Pointer.alignment; 198 | const impl = struct { 199 | fn draw(ptr: *anyopaque) void { 200 | const self = @ptrCast(Ptr, @alignCast(alignment, ptr)); 201 | drawFn(self); 202 | } 203 | fn move(ptr: *anyopaque, dx: i32, dy: i32) void { 204 | const self = @ptrCast(Ptr, @alignCast(alignment, ptr)); 205 | moveFn(self, dx, dy); 206 | } 207 | }; 208 | 209 | return .{ 210 | .ptr = obj, 211 | .drawFnPtr = impl.draw, 212 | .moveFnPtr = impl.move, 213 | }; 214 | } 215 | 216 | // define interface methods wrapping vtable func-ptrs 217 | pub fn draw(self: Shape3) void { 218 | self.drawFnPtr(self.ptr); 219 | } 220 | pub fn move(self: Shape3, dx: i32, dy: i32) void { 221 | self.moveFnPtr(self.ptr, dx, dy); 222 | } 223 | }; 224 | ``` 225 | We can test it as following: 226 | ``` zig 227 | test "vtab2_as_intf" { 228 | var data = init_data(); 229 | var shapes = [_]Shape3{ 230 | Shape3.init(&data.point, Point.draw, Point.move), 231 | Shape3.init(&data.box, Box.draw, Box.move), 232 | Shape3.init(&data.circle, Circle.draw, Circle.move), 233 | }; 234 | for (shapes) |s| { 235 | s.move(11, 22); 236 | s.draw(); 237 | } 238 | } 239 | ``` 240 | ### interface 4: old style dynamic dispatch using embedded vtab and @fieldParentPtr() ### 241 | Interface std.build.Step and all build steps std.build.[RunStep, FmtStep, ...] still use this pattern. 242 | 243 | ``` zig 244 | // define interface/vtab 245 | const Shape4 = struct { 246 | drawFn: *const fn (ptr: *Shape4) void, 247 | moveFn: *const fn (ptr: *Shape4, dx: i32, dy: i32) void, 248 | // define interface methods wrapping vtab funcs 249 | pub fn draw(self: *Shape4) void { 250 | self.drawFn(self); 251 | } 252 | pub fn move(self: *Shape4, dx: i32, dy: i32) void { 253 | self.moveFn(self, dx, dy); 254 | } 255 | }; 256 | // embed vtab and define vtab funcs as wrappers over methods 257 | const Circle4 = struct { 258 | center: Point, 259 | radius: i32, 260 | shape: Shape4, 261 | pub fn init(c: Point, r: i32) Circle4 { 262 | // define interface wrapper funcs 263 | const impl = struct { 264 | pub fn draw(ptr: *Shape4) void { 265 | const self = @fieldParentPtr(Circle4, "shape", ptr); 266 | self.draw(); 267 | } 268 | pub fn move(ptr: *Shape4, dx: i32, dy: i32) void { 269 | const self = @fieldParentPtr(Circle4, "shape", ptr); 270 | self.move(dx, dy); 271 | } 272 | }; 273 | return .{ 274 | .center = c, 275 | .radius = r, 276 | .shape = .{ .moveFn = impl.move, .drawFn = impl.draw }, 277 | }; 278 | } 279 | // the following are methods 280 | pub fn move(self: *Circle4, dx: i32, dy: i32) void { 281 | self.center.move(dx, dy); 282 | } 283 | pub fn draw(self: *Circle4) void { 284 | print("circle@<{d},{d}>radius:{d}\n", .{ self.center.x, self.center.y, self.radius }); 285 | } 286 | }; 287 | // embed vtab and define vtab funcs on struct directly 288 | const Box4 = struct { 289 | p1: Point, 290 | p2: Point, 291 | shape: Shape4, 292 | pub fn init(p1: Point, p2: Point) Box4 { 293 | return .{ 294 | .p1 = p1, 295 | .p2 = p2, 296 | .shape = .{ .moveFn = move, .drawFn = draw }, 297 | }; 298 | } 299 | //the following are vtab funcs, not methods 300 | pub fn move(ptr: *Shape4, dx: i32, dy: i32) void { 301 | const self = @fieldParentPtr(Box4, "shape", ptr); 302 | self.p1.move(dx, dy); 303 | self.p2.move(dx, dy); 304 | } 305 | pub fn draw(ptr: *Shape4) void { 306 | const self = @fieldParentPtr(Box4, "shape", ptr); 307 | print("box@<{d},{d}>-<{d},{d}>\n", .{ self.p1.x, self.p1.y, self.p2.x, self.p2.y }); 308 | } 309 | }; 310 | ``` 311 | We can test it as following: 312 | ``` zig 313 | test "vtab3_embedded_in_struct" { 314 | var box = Box4.init(Point{}, Point{ .x = 2, .y = 3 }); 315 | var circle = Circle4.init(Point{}, 5); 316 | 317 | var shapes = [_]*Shape4{ 318 | &box.shape, 319 | &circle.shape, 320 | }; 321 | for (shapes) |s| { 322 | s.move(11, 22); 323 | s.draw(); 324 | } 325 | } 326 | ``` 327 | ### interface 5: generic interface at compile time ### 328 | All above interfaces focus on vtab and dynamic dispatching: the interface values will hide the types of concrete values it holds. So you can put these interfaces values into an array and handle them uniformly. 329 | 330 | With zig's compile-time computation, you can define generic algorithms which can work with any type which provides the methods or operators required by the code in function body. For example, we can define a generic algorithm: 331 | 332 | ``` zig 333 | fn update_graphics(shape: anytype, dx: i32, dy: i32) void { 334 | shape.move(dx, dy); 335 | shape.draw(); 336 | } 337 | ``` 338 | As shown above, "shape" can be anytype as long as it provides move() and draw() methods. All type checking happen at comptime and no dynamic dispatching. 339 | 340 | As following, we can define a generic interface which capture the methods required by some generic algorithm; and we can use it to adapt some types/instances with different method names into the required api. 341 | 342 | Interface std.io.[Reader, Writer] and std.fifo and std.fs.File use this pattern. 343 | 344 | Since these generic interfaces do not erase the type info of the values it hold, they are different types. Thus you cannot put them into an array for handling uniformally. 345 | 346 | ``` zig 347 | pub fn Shape5( 348 | comptime Pointer: type, 349 | comptime drawFn: *const fn (ptr: Pointer) void, 350 | comptime moveFn: *const fn (ptr: Pointer, dx: i32, dy: i32) void, 351 | ) type { 352 | return struct { 353 | ptr: Pointer, 354 | const Self = @This(); 355 | pub fn init(p: Pointer) Self { 356 | return .{ .ptr = p }; 357 | } 358 | // interface methods wrapping passed-in funcs/methods 359 | pub fn draw(self: Self) void { 360 | drawFn(self.ptr); 361 | } 362 | pub fn move(self: Self, dx: i32, dy: i32) void { 363 | moveFn(self.ptr, dx, dy); 364 | } 365 | }; 366 | } 367 | 368 | //a generic algorithms use duck-typing/static dispatch. 369 | //note: shape can be "anytype" which provides move()/draw() 370 | fn update_graphics(shape: anytype, dx: i32, dy: i32) void { 371 | shape.move(dx, dy); 372 | shape.draw(); 373 | } 374 | 375 | //define a TextArea with similar but diff methods 376 | const TextArea = struct { 377 | position: Point, 378 | text: []const u8, 379 | pub fn init(pos: Point, txt: []const u8) TextArea { 380 | return .{ .position = pos, .text = txt }; 381 | } 382 | pub fn relocate(self: *TextArea, dx: i32, dy: i32) void { 383 | self.position.move(dx, dy); 384 | } 385 | pub fn display(self: *TextArea) void { 386 | print("text@<{d},{d}>:{s}\n", .{ self.position.x, self.position.y, self.text }); 387 | } 388 | }; 389 | ``` 390 | We can test it as following: 391 | 392 | ``` zig 393 | test "generic_interface" { 394 | var box = Box.init(Point{}, Point{ .x = 2, .y = 3 }); 395 | //apply generic algorithms to matching types directly 396 | update_graphics(&box, 11, 22); 397 | var textarea = TextArea.init(Point{}, "hello zig!"); 398 | //use generic interface to adapt non-matching types 399 | var drawText = Shape5(*TextArea, TextArea.display, TextArea.relocate).init(&textarea); 400 | update_graphics(drawText, 4, 5); 401 | } 402 | ``` 403 | -------------------------------------------------------------------------------- /interfaces.zig: -------------------------------------------------------------------------------- 1 | const std = @import("std"); 2 | const assert = std.debug.assert; 3 | const print = std.debug.print; 4 | 5 | //--- define a few "shapes": point, box, circle --- 6 | const Point = struct { 7 | x: i32 = 0, 8 | y: i32 = 0, 9 | pub fn move(self: *Point, dx: i32, dy: i32) void { 10 | self.x += dx; 11 | self.y += dy; 12 | } 13 | pub fn draw(self: *Point) void { 14 | print("point@<{d},{d}>\n", .{ self.x, self.y }); 15 | } 16 | }; 17 | 18 | const Box = struct { 19 | p1: Point, 20 | p2: Point, 21 | pub fn init(p1: Point, p2: Point) Box { 22 | return .{ .p1 = p1, .p2 = p2 }; 23 | } 24 | pub fn move(self: *Box, dx: i32, dy: i32) void { 25 | self.p1.move(dx, dy); 26 | self.p2.move(dx, dy); 27 | } 28 | pub fn draw(self: *Box) void { 29 | print("box@<{d},{d}>-<{d},{d}>\n", .{ self.p1.x, self.p1.y, self.p2.x, self.p2.y }); 30 | } 31 | }; 32 | 33 | const Circle = struct { 34 | center: Point, 35 | radius: i32, 36 | pub fn init(c: Point, r: i32) Circle { 37 | return .{ .center = c, .radius = r }; 38 | } 39 | pub fn move(self: *Circle, dx: i32, dy: i32) void { 40 | self.center.move(dx, dy); 41 | } 42 | pub fn draw(self: *Circle) void { 43 | print("circle@<{d},{d}>radius:{d}\n", .{ self.center.x, self.center.y, self.radius }); 44 | } 45 | }; 46 | 47 | //create a set of "shapes" for test 48 | fn init_data() struct { point: Point, box: Box, circle: Circle } { 49 | return .{ 50 | .point = Point{}, 51 | .box = Box.init(Point{}, Point{ .x = 2, .y = 3 }), 52 | .circle = Circle.init(Point{}, 5), 53 | }; 54 | } 55 | 56 | //--- interface1: enum tagged union --- 57 | const Shape1 = union(enum) { 58 | point: *Point, 59 | box: *Box, 60 | circle: *Circle, 61 | pub fn move(self: Shape1, dx: i32, dy: i32) void { 62 | switch (self) { 63 | inline else => |s| s.move(dx, dy), 64 | } 65 | } 66 | pub fn draw(self: Shape1) void { 67 | switch (self) { 68 | inline else => |s| s.draw(), 69 | } 70 | } 71 | }; 72 | 73 | test "union_as_intf" { 74 | var data = init_data(); 75 | var shapes = [_]Shape1{ 76 | .{ .point = &data.point }, 77 | .{ .box = &data.box }, 78 | .{ .circle = &data.circle }, 79 | }; 80 | print("\n", .{}); 81 | for (shapes) |s| { 82 | s.move(11, 22); 83 | s.draw(); 84 | } 85 | } 86 | 87 | //--- interface2: 1st variant of vtable --- 88 | // std.mem.Allocator works this way 89 | const Shape2 = struct { 90 | // define interface fields: ptr,vtab 91 | ptr: *anyopaque, //ptr to instance 92 | vtab: *const VTab, //ptr to vtab 93 | const VTab = struct { 94 | draw: *const fn (ptr: *anyopaque) void, 95 | move: *const fn (ptr: *anyopaque, dx: i32, dy: i32) void, 96 | }; 97 | 98 | // define interface methods wrapping vtable calls 99 | pub fn draw(self: Shape2) void { 100 | self.vtab.draw(self.ptr); 101 | } 102 | pub fn move(self: Shape2, dx: i32, dy: i32) void { 103 | self.vtab.move(self.ptr, dx, dy); 104 | } 105 | 106 | // cast concrete objects/types to interface 107 | pub fn init(obj: anytype) Shape2 { 108 | const Ptr = @TypeOf(obj); 109 | const PtrInfo = @typeInfo(Ptr); 110 | assert(PtrInfo == .Pointer); // Must be a pointer 111 | assert(PtrInfo.Pointer.size == .One); // Must be a single-item pointer 112 | assert(@typeInfo(PtrInfo.Pointer.child) == .Struct); // Must point to a struct 113 | const alignment = PtrInfo.Pointer.alignment; 114 | const impl = struct { 115 | fn draw(ptr: *anyopaque) void { 116 | const self = @ptrCast(Ptr, @alignCast(alignment, ptr)); 117 | 118 | self.draw(); 119 | } 120 | fn move(ptr: *anyopaque, dx: i32, dy: i32) void { 121 | const self = @ptrCast(Ptr, @alignCast(alignment, ptr)); 122 | 123 | self.move(dx, dy); 124 | } 125 | }; 126 | return .{ 127 | .ptr = obj, 128 | .vtab = &.{ 129 | .draw = impl.draw, 130 | .move = impl.move, 131 | }, 132 | }; 133 | } 134 | }; 135 | 136 | test "vtab1_as_intf" { 137 | var data = init_data(); 138 | var shapes = [_]Shape2{ 139 | Shape2.init(&data.point), 140 | Shape2.init(&data.box), 141 | Shape2.init(&data.circle), 142 | }; 143 | print("\n", .{}); 144 | for (shapes) |s| { 145 | s.move(11, 22); 146 | s.draw(); 147 | } 148 | } 149 | 150 | //--- interface3: 2nd variant of vtable --- 151 | // std.rand.Random works this way; 152 | const Shape3 = struct { 153 | // define interface fields: ptr,vtab 154 | // ptr to instance 155 | ptr: *anyopaque, 156 | // inline vtable 157 | drawFnPtr: *const fn (ptr: *anyopaque) void, 158 | moveFnPtr: *const fn (ptr: *anyopaque, dx: i32, dy: i32) void, 159 | 160 | pub fn init( 161 | obj: anytype, 162 | comptime drawFn: fn (ptr: @TypeOf(obj)) void, 163 | comptime moveFn: fn (ptr: @TypeOf(obj), dx: i32, dy: i32) void, 164 | ) Shape3 { 165 | const Ptr = @TypeOf(obj); 166 | assert(@typeInfo(Ptr) == .Pointer); // Must be a pointer 167 | assert(@typeInfo(Ptr).Pointer.size == .One); // Must be a single-item pointer 168 | assert(@typeInfo(@typeInfo(Ptr).Pointer.child) == .Struct); // Must point to a struct 169 | const alignment = @typeInfo(Ptr).Pointer.alignment; 170 | const impl = struct { 171 | fn draw(ptr: *anyopaque) void { 172 | const self = @ptrCast(Ptr, @alignCast(alignment, ptr)); 173 | drawFn(self); 174 | } 175 | fn move(ptr: *anyopaque, dx: i32, dy: i32) void { 176 | const self = @ptrCast(Ptr, @alignCast(alignment, ptr)); 177 | moveFn(self, dx, dy); 178 | } 179 | }; 180 | 181 | return .{ 182 | .ptr = obj, 183 | .drawFnPtr = impl.draw, 184 | .moveFnPtr = impl.move, 185 | }; 186 | } 187 | 188 | // define interface methods wrapping vtable func-ptrs 189 | pub fn draw(self: Shape3) void { 190 | self.drawFnPtr(self.ptr); 191 | } 192 | pub fn move(self: Shape3, dx: i32, dy: i32) void { 193 | self.moveFnPtr(self.ptr, dx, dy); 194 | } 195 | }; 196 | 197 | test "vtab2_as_intf" { 198 | var data = init_data(); 199 | var shapes = [_]Shape3{ 200 | Shape3.init(&data.point, Point.draw, Point.move), 201 | Shape3.init(&data.box, Box.draw, Box.move), 202 | Shape3.init(&data.circle, Circle.draw, Circle.move), 203 | }; 204 | print("\n", .{}); 205 | for (shapes) |s| { 206 | s.move(11, 22); 207 | s.draw(); 208 | } 209 | } 210 | 211 | //--- interface4: embed vtab in concrete types --- 212 | // std.build.Step works this way 213 | // define interface/vtab 214 | const Shape4 = struct { 215 | drawFn: *const fn (ptr: *Shape4) void, 216 | moveFn: *const fn (ptr: *Shape4, dx: i32, dy: i32) void, 217 | // define interface methods wrapping vtab funcs 218 | pub fn draw(self: *Shape4) void { 219 | self.drawFn(self); 220 | } 221 | pub fn move(self: *Shape4, dx: i32, dy: i32) void { 222 | self.moveFn(self, dx, dy); 223 | } 224 | }; 225 | // embed vtab and define vtab funcs as wrappers over methods 226 | const Circle4 = struct { 227 | center: Point, 228 | radius: i32, 229 | shape: Shape4, 230 | pub fn init(c: Point, r: i32) Circle4 { 231 | // define interface wrapper funcs 232 | const impl = struct { 233 | pub fn draw(ptr: *Shape4) void { 234 | const self = @fieldParentPtr(Circle4, "shape", ptr); 235 | self.draw(); 236 | } 237 | pub fn move(ptr: *Shape4, dx: i32, dy: i32) void { 238 | const self = @fieldParentPtr(Circle4, "shape", ptr); 239 | self.move(dx, dy); 240 | } 241 | }; 242 | return .{ 243 | .center = c, 244 | .radius = r, 245 | .shape = .{ .moveFn = impl.move, .drawFn = impl.draw }, 246 | }; 247 | } 248 | // the following are methods 249 | pub fn move(self: *Circle4, dx: i32, dy: i32) void { 250 | self.center.move(dx, dy); 251 | } 252 | pub fn draw(self: *Circle4) void { 253 | print("circle@<{d},{d}>radius:{d}\n", .{ self.center.x, self.center.y, self.radius }); 254 | } 255 | }; 256 | // embed vtab and define vtab funcs on struct directly 257 | const Box4 = struct { 258 | p1: Point, 259 | p2: Point, 260 | shape: Shape4, 261 | pub fn init(p1: Point, p2: Point) Box4 { 262 | return .{ 263 | .p1 = p1, 264 | .p2 = p2, 265 | .shape = .{ .moveFn = move, .drawFn = draw }, 266 | }; 267 | } 268 | //the following are vtab funcs, not methods 269 | pub fn move(ptr: *Shape4, dx: i32, dy: i32) void { 270 | const self = @fieldParentPtr(Box4, "shape", ptr); 271 | self.p1.move(dx, dy); 272 | self.p2.move(dx, dy); 273 | } 274 | pub fn draw(ptr: *Shape4) void { 275 | const self = @fieldParentPtr(Box4, "shape", ptr); 276 | print("box@<{d},{d}>-<{d},{d}>\n", .{ self.p1.x, self.p1.y, self.p2.x, self.p2.y }); 277 | } 278 | }; 279 | 280 | test "vtab3_embedded_in_struct" { 281 | var box = Box4.init(Point{}, Point{ .x = 2, .y = 3 }); 282 | var circle = Circle4.init(Point{}, 5); 283 | 284 | var shapes = [_]*Shape4{ 285 | &box.shape, 286 | &circle.shape, 287 | }; 288 | print("\n", .{}); 289 | for (shapes) |s| { 290 | s.move(11, 22); 291 | s.draw(); 292 | } 293 | } 294 | 295 | //--- interface5: generic interface at compile time --- 296 | // api/method-set adaptor: wrap obj methods to a method-set 297 | // required by generic algorithms, static dispatch (generics) 298 | // std.io.(Reader/Writer) work this way 299 | pub fn Shape5( 300 | comptime Pointer: type, 301 | comptime drawFn: *const fn (ptr: Pointer) void, 302 | comptime moveFn: *const fn (ptr: Pointer, dx: i32, dy: i32) void, 303 | ) type { 304 | return struct { 305 | ptr: Pointer, 306 | const Self = @This(); 307 | pub fn init(p: Pointer) Self { 308 | return .{ .ptr = p }; 309 | } 310 | // interface methods wrapping passed-in funcs/methods 311 | pub fn draw(self: Self) void { 312 | drawFn(self.ptr); 313 | } 314 | pub fn move(self: Self, dx: i32, dy: i32) void { 315 | moveFn(self.ptr, dx, dy); 316 | } 317 | }; 318 | } 319 | 320 | //a generic algorithms use duck-typing/static dispatch. 321 | //note: shape can be "anytype" which provides move()/draw() 322 | fn update_graphics(shape: anytype, dx: i32, dy: i32) void { 323 | shape.move(dx, dy); 324 | shape.draw(); 325 | } 326 | 327 | //define a TextArea with similar but diff methods 328 | const TextArea = struct { 329 | position: Point, 330 | text: []const u8, 331 | pub fn init(pos: Point, txt: []const u8) TextArea { 332 | return .{ .position = pos, .text = txt }; 333 | } 334 | pub fn relocate(self: *TextArea, dx: i32, dy: i32) void { 335 | self.position.move(dx, dy); 336 | } 337 | pub fn display(self: *TextArea) void { 338 | print("text@<{d},{d}>:{s}\n", .{ self.position.x, self.position.y, self.text }); 339 | } 340 | }; 341 | 342 | test "generic_interface" { 343 | var box = Box.init(Point{}, Point{ .x = 2, .y = 3 }); 344 | print("\n", .{}); 345 | //apply generic algorithms to matching types directly 346 | update_graphics(&box, 11, 22); 347 | var textarea = TextArea.init(Point{}, "hello zig!"); 348 | //use generic interface to adapt non-matching types 349 | var drawText = Shape5(*TextArea, TextArea.display, TextArea.relocate).init(&textarea); 350 | update_graphics(drawText, 4, 5); 351 | } 352 | --------------------------------------------------------------------------------