Zig (programming language): Difference between revisions

Content deleted Content added
m Versions: Column cleaning. Merge x86 & i386.
top: Fixed a comma splice
Tags: Mobile edit Mobile app edit Android app edit App full source
Line 66:
In this code, the {{code|allocator}} variable is passed a struct that describes what code should perform the allocation, and the {{code|repeat}} function returns either the resulting string or, using the optional type as indicated by the {{code|!}}, an Allocator.Error. By directly expressing the allocator as an input, memory allocation is never "hidden" within another function, it is always exposed to the API by the function that is ultimately calling for the memory to be allocated. No allocations are performed inside Zig’s [[standard library]]. Further, as the struct can point to anything, one can use alternative allocators, even ones written in the program. This can allow, for instance, small-object allocators that do not use the [[operating system]] functions that normally allocate an entire [[memory page]].<ref name=zigo>{{cite web |url=https://ziglearn.org/chapter-2/ |title=Allocators|date=11 September 2023 }}</ref>
 
Optional types are an example of a language feature that offers general functionality while still being simple and generic. They do not have to be used to solve null pointer problems,; they are also useful for any type of value where "no value" is an appropriate answer. Consider a function {{code|countTheNumberOfUsers}} that returns an integer, and an integer variable, {{code|theCountedUsers}} that holds the result. In many languages, a [[Magic number (programming)|magic number]] would be placed in {{code|theCountedUsers}} to indicate that {{code|countTheNumberOfUsers}} has not yet been called, while many implementations would just set it to zero. In Zig, this could be implemented as an {{code|var theCountedUsers: ?i32 {{=}} null|lang=zig}} which sets the variable to a clear "not been called" value.<ref name=zigo/>
 
Another more general feature of Zig that also helps manage memory problems is the concept of {{code|defer}}, which marks some code to be performed at the end of a function no matter what happens, including possible runtime errors. If a particular function allocates some memory and then disposes of it when the operation is complete, one can add a line to defer a {{code|free}} to ensure it is released no matter what happens.<ref name=zigo/>