Thanks for using Compiler Explorer
Sponsors
Jakt
C++
Ada
Analysis
Android Java
Android Kotlin
Assembly
C
C3
Carbon
C++ (Circle)
CIRCT
Clean
CMake
CMakeScript
COBOL
C++ for OpenCL
MLIR
Cppx
Cppx-Blue
Cppx-Gold
Cpp2-cppfront
Crystal
C#
CUDA C++
D
Dart
Elixir
Erlang
Fortran
F#
GLSL
Go
Haskell
HLSL
Hook
Hylo
IL
ispc
Java
Julia
Kotlin
LLVM IR
LLVM MIR
Modula-2
Nim
Objective-C
Objective-C++
OCaml
OpenCL C
Pascal
Pony
Python
Racket
Ruby
Rust
Snowball
Scala
Solidity
Spice
SPIR-V
Swift
LLVM TableGen
Toit
TypeScript Native
V
Vala
Visual Basic
WASM
Zig
Javascript
GIMPLE
Ygen
zig source #1
Output
Compile to binary object
Link to binary
Execute the code
Intel asm syntax
Demangle identifiers
Verbose demangling
Filters
Unused labels
Library functions
Directives
Comments
Horizontal whitespace
Debug intrinsics
Compiler
zig 0.10.0
zig 0.11.0
zig 0.12.0
zig 0.12.1
zig 0.13.0
zig 0.2.0
zig 0.3.0
zig 0.4.0
zig 0.5.0
zig 0.6.0
zig 0.7.0
zig 0.7.1
zig 0.8.0
zig 0.9.0
zig trunk
Options
Source code
//// Qn to #zig: Is this the idiomatic way of writing a generic "class"? //// Another qn: How do we write interface in zig? //// I couldn't find resources on this, but I think I can hand-roll //// my own interface by using comptime @asserts fn SliceStream(comptime Elem: type) type { return struct { data: []const Elem, pos: usize, pub fn peek(self: SliceStream(Elem)) ?Elem { if (self.pos >= self.data.len) { return null; } else { return self.data[self.pos]; } } //// The real qn: //// I needed a way to construct a value of this type //// So are we supposed to put our "constructors" in the type itself? //// It seems to lead to this funny recursive syntax here //// | //// v pub fn slice_stream(data: []const Elem) SliceStream(Elem) { return .{.data = data, .pos = 0 }; } }; } export fn fancy_id(num: i32) i32 { const my_data = [_]i32{num, num, num}; // Instantiates the type for our particular data // Similar to vector<i32> if using C++ const I32SliceStream = SliceStream(i32); // calls the "constructor" which I put as a function in the class // I guess this would be something like vector<i32>::vector<i32>(...) const my_stream = I32SliceStream.slice_stream(my_data[0..3]); // call the method. // obj.method() gets rewritten to @Typeof(obj).method(obj) // So it's like python. return (my_stream.peek()).?; } pub fn main() u8 { return @intCast(u8, fancy_id(5)); }
Become a Patron
Sponsor on GitHub
Donate via PayPal
Source on GitHub
Mailing list
Installed libraries
Wiki
Report an issue
How it works
Contact the author
CE on Mastodon
About the author
Statistics
Changelog
Version tree