Skip to content

proposal: Go 2: default initializers for types #32076

@deanveloper

Description

@deanveloper

Default Initializers

I'm not sure what reminded me of this idea. This is an offshoot of #28939 which was closed, however there was still discussion about default initializers which shortly died off. I figured I would create a quick proposal about how this would work.

Goal

The goal of default initializers is to allow types to have default state when initialized. This helps reduce boilerplate code at both the declaration site and the call site.

Declaration Syntax

There are two syntaxes that will be brought up.

Syntax 1:

type Foo struct {
    X int = 5
    Y float64 = 7
    unexported time.Duration = 5 * time.Second
}

Syntax 2:

type Foo struct {
    X int
    Y float64

    unexported time.Duration
} default {
    X: 5
    Y: 7
    unexported: 5 * time.Second
}
  • Syntax 1
    • A bit more intiuitive, less boilerplate
  • Syntax 2
    • Closer to struct creation syntax
    • Allows for shorter lines when declaring default values for variables with long type signatures
    • type Bar uint default 5 Allows for default values for non-struct values

Call Site

var f Foo // should definitely use default initializer

f := Foo{} // Foo{5,7}
f := Foo{Y: 10} // Foo{5,10}

The reason that Foo{Y:10} resolves to Foo{5,10} and not Foo{0,10} is for consistent behavior with unexported variables. Also this prevents people from trying to be "clever" by writing code that is less readable, and prevents subtle bugs from changing Foo{} to Foo{Y:10}.

Note - the following two functions remain equivalent, just as they are in current Go:

func NewFoo1() Foo {
    return Foo{Y: 10203}
}

func NewFoo2() Foo {
    var f Foo
    f.Y = 10203
    return f
}

Footnote

I'm personally not sure what to think about this proposal. I mainly made it since it's been discussed before but there was no proposal made for it yet. I know some people would like it since it reduces boilerplate code, while others would say it adds bloat to the language and makes the call-site less predictable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions