#add functions to a data type.

1 messages · Page 1 of 1 (latest)

shrewd sequoia
#

Suppose I want to add functions to a pre-existing datatype:
var x:[]const u8 = "hello";
x.reverse()
I want to create a reverse function for x.

I don't want to do reverse(x), but want to create a function that would work like: x.reverse().

opaque pollen
shrewd sequoia
#

so, what if I do:
const str = []const u8;

opaque pollen
#

that's not a new type, it's a type alias

shrewd sequoia
#

maybe?

var mycustom:ByteString.inner = "Hello";

Like this?

opaque pollen
#

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

shrewd sequoia
#

hmm thanks alot!

opaque pollen
# shrewd sequoia 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

shrewd sequoia
#

like any possible way? (maybe use of C)?

opaque pollen
#

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

shrewd sequoia
#

Oh! now I understood the whole thing thanks alot!!

opaque pollen
#

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