Skip to content

Object init shorthand #418

@dom96

Description

@dom96

Consider the following object type:

type
  User = object
    name: string
    age: int
    last_online: float

It's very common to write a constructor for such types, some may have many more fields than the above, having to write the name of each field gets tedious:

proc initUser(name: string, age: int): User =
  User(
    name: name,
    age: age,
    last_online: epochTime()
  )

This RFC proposes to implement a short-hand syntax for the object construction syntax to simplify this code:

proc initUser(name: string, age: int): User =
  User(
    name,
    age,
    last_online: epochTime()
  )

The variable names have to match that of the field name, so User(foo, age) won't work even if foo is a string.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions