Hacker News new | ask | show | jobs
by lossolo 3075 days ago
Zig looks very interesting. There is only TODO in memory section in documentation. From what I understand there is only manual memory management? I've seen there is a mention about custom allocators, any details? Any RAII like concept? or full manual memory management?
2 comments

"Zig does not support RAII or operator overloading because both make it very difficult to tell where function calls happen just by looking at a function body."

more in the 0.1.1 release notes! http://ziglang.org/download/0.1.1/release-notes.html

"Zig's standard library is still very young, but the goal is for every feature that uses an allocator to accept an allocator at runtime, or possibly at either compile time or runtime."

more in this wiki! https://github.com/zig-lang/zig/wiki/Why-Zig-When-There-is-A...

>"Zig does not support RAII or operator overloading because both make it very difficult to tell where function calls happen just by looking at a function body."

How about showing an error if you don't call the deconstructor manually?

Memory is manually managed, yes. We do have defer (as in go) for slightly easier resource management.

Zig doesn't have a default memory allocator. Allocators instead are expected to be passed as an argument to functions as they need them. This makes it trivial to replace an allocator with something custom or use multiple different allocators within a small code block.

A contrived example:

  const std = @import("std");

  pub fn GiveMeAnInt(alloc: &std.mem.Allocator) -> %&u32 {
      return alloc.create(u32);
  }

  test "using two allocators" {
      const int1 = try GiveMeAnInt(std.heap.c_allocator);
      *int1 = 2;
      // Would usually store the allocator with the type on construction.
      defer std.heap.c_allocator.destroy(int1);

      const int2 = try GiveMeAnInt(std.debug.global_allocator);
      *int2 = 2;
  }