#Methods on tuples

1 messages · Page 1 of 1 (latest)

grim quartz
#

If I have for example a tuple const Foo = .{u8};. Is there a way I can define methods on it?

sterile mist
#

Not to be rude but, why would you want to do this?

sharp pecan
#

you can always just wrap it in a struct
but no, tuples cant have methods

grim quartz
#

👍

grim quartz
sharp pecan
#

but also yeah, id highly recommend treating structs/tuples as data, not objects
you dont need methods

#

see that's a perfect example, you can see std.crypto which just directly takes in and returns arrays like that without wrapping them in any types

grim quartz
#

I tried using that style and I found it to be annoying because I can toss any [_]u8 in it which is kind of annoying. I think wrapping it ensures that it contains the data I want. I did the same thing with my timestamp. I'm working on rewriting this from a rust implementation which I had struct Timestamp(u128) which I defined a new method on that simple got the time in nanos. I prefered this since I couldn't accidentaly just pass in a random number.

#

@sharp pecan

sharp pecan
#

well that's a personal design decision ig
but you can still just have the function take in a Hash without it being a method

sterile mist
#

will std.mem.Allocator.realloc allocate if i pass it a null pointer but how do i even pass it a null pointer.

#

oops wrong place

quick anvil
#

Well you could define a struct to have tuple semantics by writing a normal struct, but instead of specifying each field with name: type, just write type. So for your example, struct { u8, }
You can have a method on it like a normal struct:

const FooStructure = struct {
  u8,
  const Self = @This();
  fn doAThing(self: Self) void {
    // Just write this out like a normal method
  }
};
hot sundial
#

main.zig:5:3: error: tuple declarations cannot contain declarations

upbeat kiln
#

I think that works fine enough

quick anvil
#

whoops, sorry for the confusion

sudden scroll
sharp pecan
#

generally you should avoid init unless you actually need it

upbeat kiln
#

tbh I never actually use init anyway, but you're right