我刚刚开始使用Zig,来自c++和Rust;
我很早就遇到了一个我似乎无法解决的难题。或者在网上随便找。
这是我的:
// this doesn't work
pub const User = struct {
bot: bool,
id: *const [*:0]u8,
username: *const [*:0]u8,
pub fn init() User {
return User {
.bot = false,
.id = "THIS_IS_ID",
.username = "THIS_IS_USERNAME"
};
}
...
}
const user = User.init();
// this works vvv
id: *const [10:0]u8,
.id = "THIS_IS_ID",
这是我得到的错误:
error: expected type '*const [*:0]u8', found '*const [10:0]u8'
.id = "THIS_IS_ID",
我的目标,我试图摆脱问这个问题是要知道是否有可能有动态字符串在zig;如果有,又是怎样的呢?我在网上看到过一些自定义字符串结构,但我想知道是否有一种方法可以在不为它创建单独的类型/结构的情况下实现这一点…?
谢谢你的帮助!
使用[]const u8
或[]u8
。查看切片的文档。
const
变化:
// Can assign string literals
var id: []const u8 = "THIS_IS_ID";
// vs
// var id: []u8 = "THIS_IS_ID";
// ^~~~~~~~~~~~
// error: expected type '[]u8', found '*const [10:0]u8'
// note: cast discards const qualifier
// But cannot change individual bytes
std.mem.copy(u8, id, "THIS_IS_ANOTHER_ID");
// ^~
// error: expected type '[]u8', found '[]const u8'
// note: cast discards const qualifier
你必须决定谁拥有内存:
- 可以是每个单独的变量,也可以是一个字段。 或者一个单独的内存缓冲区,或者一个分配器。
我真的不太了解问题的范围(或zig),但我认为您需要这样做:
- 对于动态字符串(分配),您需要确保您有一个分配器为字符串分配一些内存。
// you can use any allocator you prefer
const allocator = std.heap.page_allocator;
- 你需要为你想要存储的字符串分配一些空间
// here we allocate some memory for the string we want to store
// we allocate some memory for 10 bytes (which can store
// a string having at most 10 characters)
// NOTE: the operation could fail, hence the `try`
var slice = try allocator.alloc(u8, 10);
- 最后,将您想要存储的字符串写入分配的缓冲区/切片
// we write the string we want to store into the slice (or
// buffer) we previously allocated above
// NOTE: the operation could fail, hence the `try`. Also,
// the function returns a slice of the buffer printed to.
_ = try std.fmt.bufPrint(slice, "hello", .{});
// you can print out the contents of the slice (or buffer)
std.debug.print("{s}", .{slice});
如前所述,看起来您想要不可变的.id
和.username
字符串。在这种情况下,你可以这样做:
struct {
id: []const u8,
username: []const u8,
…代替:
struct {
id: *const [*:0]u8,
username: *const [*:0]u8,
…,然后您可以将它们分配给字面量,如'。id = "THIS_IS_ID".
如果您想要可变字符串,那么使用std.mem.Allocator
中的dupe
,如下所示。
const id = try allocator.dupe(u8, "THIS_IS_ID");
errdefer allocator.free(id);
const username = try allocator.dupe(u8, "THIS_IS_USERNAME");
return User {
.bot = false,
.id = id,
.username = username,
};
Zig强制您以这种方式显式地获得新内存的所有权。