#add functions to a data type.
1 messages · Page 1 of 1 (latest)
you cant do that (for very good reason) without wrapping it in your own custom type like
const ByteString = struct {
inner: []const u8,
pub fn reverse(bs: *ByteString) void { ... }
};
so, what if I do:
const str = []const u8;
that's not a new type, it's a type alias
so, how will this work like:
var mycustom:ByteString = "Hello";
Like this?
maybe?
var mycustom:ByteString.inner = "Hello";
Like this?
nope, that would only work if @TypeOf("Hello") coerces to ByteString
which it does not
youd need to do
var mycustom = ByteString{.inner = "Hello" };
also keep in mind that the inner field will be a []const u8 so it wont be able to modify it's inner string
hmm thanks alot!
id personally recommend just not doing this btw
dont think of structs as objects that you interact with by the functions they provide
think of structs as data with namespace
std.mem.reverse(u8, str) is better than str.reverse() because it's just treating the string as data and being very explicit that it's doing it generically
also, is it possible to create something like this:
var mycustom:ByteString = "Hello";
ByteString.reverse()
?
like any possible way? (maybe use of C)?
im not sure what you mean
"Hello" wont ever be able to coerce to any custom type
doesnt matter what you do
and ByteString.reverse() would just be calling the reverse function in the ByteString namespace
Oh! now I understood the whole thing thanks alot!!
really though, dont try to do things with zig that the language doesnt let you do
there's a reason you cant coerce string literals to your type
and a reason for why using a wrapper struct isnt very convenient
zig naturally leads you towards good practices and a readable code base, dont try to fight it