V: Constructors for structs

Created on 2 Oct 2019  路  3Comments  路  Source: vlang/v

It seems that structs are missing constructors now.

Any intent to add them?

Feature Request

Most helpful comment

Yes, you can use a function for that:

fn new_mystruct(value string) MyStruct{
  return MyStruct{
   value: value
   _id: unique_hash_id()
  }
}
mut my := new_mystruct(value)

V is a simple language. Besides, structs are not classes, there's no OOP in V.

All 3 comments

No, just like in Go, structs can be constructed with functions, like new_foo().

I mean what if some background work should be done on initialization? Assigning unique hash to _id field, for example:

struct Mystruct {
  _id int
  value string
}

fn (m mut Mystruct) __constructor() {
  m._id = unique_hash_id()
}

mut my := Mystruct{value: "value"}

Yes, you can use a function for that:

fn new_mystruct(value string) MyStruct{
  return MyStruct{
   value: value
   _id: unique_hash_id()
  }
}
mut my := new_mystruct(value)

V is a simple language. Besides, structs are not classes, there's no OOP in V.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

XVilka picture XVilka  路  3Comments

radare picture radare  路  3Comments

markgraydev picture markgraydev  路  3Comments

penguindark picture penguindark  路  3Comments

medvednikov picture medvednikov  路  3Comments