Ask Your Question
1

Is it possible to have dynamic strings in Zig?

asked 2022-10-23 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-08-31 12:00:00 +0000

bukephalos gravatar image

Yes, it is possible to have dynamic strings in Zig.

Zig provides two main types of strings: fixed-length strings and resizable strings. Fixed-length strings have a specific size that is determined at compile time, while resizable strings can grow or shrink dynamically at runtime.

Here is an example of creating a resizable string and appending to it:

const std = @import("std");

var builder = std.heap.ManagedStringBuilder.init(std.heap.page_allocator);
defer builder.deinit();

builder.append("Hello, ");
builder.append("world!");

var str = builder.to_string();
std.debug.print("Resized string: {}\n", .{str});

In this example, we first initialize a ManagedStringBuilder with a page allocator from the standard library. We use append() to add two separate strings to the builder, and then we call to_string() to get a []u8 slice representing the final string.

Note that ManagedStringBuilder uses a heap allocator, so you need to ensure the memory is properly managed by calling deinit().

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-10-23 11:00:00 +0000

Seen: 16 times

Last updated: Aug 31 '22