2

In V language methods are defined separately from the data structures.

Does the V language allow to define methods on base types, like Array?

Is it possible to write my_method method like

fn (array Array) my_method() { ... }

list := ["a", "b"]
list.my_method()
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
Alex Craft
  • 13,598
  • 11
  • 69
  • 133
  • 1
    I don't believe so... I get `error: cannot define new methods on non-local `array_int`` when I try it. Unlike Ruby, I guess we don't extend other module's data structures. – aMike Jun 13 '20 at 12:03

2 Answers2

3

Only in your own modules were you control the implementation - and I don't think there's any plans to support it.

You might do something like it with either generics or struct embeds, when they're fully done. But I doubt there'll be support for it for builtin module types.

Edit: (In the future it might also be possible to do something with Sum types)

Larpon
  • 812
  • 6
  • 19
1

You can't define a method on a type unless the type and method are both defined in the same module. However you can define a method on an array of a custom type if both the method and the custom type are in the same module. For example:

struct St
{
    i int
}

fn (s []St) array_method() {
    println(s[0])
    println(s[1])
}

arr := [St{3}, St{4}]
arr.array_method()