It would be very nice to allow something like this:
struct Abc {
name string
// all other fields
fn (a Abc) is_empty() bool {
return a.name.len == 0
}
// all other funcs
}
This imply the use of type Abc before its complete definition.
I would add method definition inside structs AFTER all fields have been declared, as shown above.
This would greatly simulate OOP without changing the language
In this case, (a Abc) will not be required. like this:
struct Abc {
name string
fn is_empty() bool {
return this.name.len == 0
}
}
When I was learning Go and Rust, I was wondering about the benefit of separating the method from the body struct.
Their merging into one body struct seemed more friendly and clear in reading. I do not know.
But I got used to this. I don't think it is so important
Yes, merging methods inside parent data-structure is more friendly and clear in reading.
That's why I asked for it.
Your synthax with this keyword is equivalent and shorter, but requires changing the actual parser.
Both ways would be good
I like the idea, I'm used to that way of writing methods (from C#, C++, etc ...), it would be great if you could do that in V.
BTW, in addition to this you could use self like in Rust/Python.
struct Abc {
name string
// like in Python (without `self` parameter)
fn is_empty() bool {
return self.name.len == 0
}
// or like in Rust
fn is_empty(self) bool {
return self.name.len == 0
}
fn is_empty_mut(mut self) bool {
return self.name.len == 0
}
fn is_empty_ref(&self) bool {
return self.name.len == 0
}
}
Why do you need to declare the functions inside the struct? This already works:
struct Abc {
name string
// all other fields
}
fn (a Abc) is_empty() bool {
return a.name.len == 0
}
// all other funcs
Since it references a, it will be a per-instance reference. No need for self or other placeholders.
In this case, (a Abc) will not be required.
But sometimes we need a receiver of type &Abc or a mutable receiver.
@ntrel You are right
Most helpful comment
Why do you need to declare the functions inside the struct? This already works:
Since it references
a, it will be a per-instance reference. No need forselfor other placeholders.