Skip to content

proposal: Go 2: required fields on struct #28348

Closed
@cyberhck

Description

@cyberhck

This issue describes a language feature proposal to structs.
Depending on which path we take this might or might not break backwards compatibility.

Background

Say we have a API SDK, which can't function without http endpoint, api token, in other words, endpoint and api token are required, but user may or may not provide HttpClient (if he wishes to overwrite)

As of now, I'd say my struct would look something like this:

struct Options {
  Endpoint string
  Token string
  Client HttpClient
}

Just by looking at this someone doesn't know what to do, and if they don't pass in Token, it just crashes in Runtime:

x := Options {Endpoint: ""} // crashes during run time, not even on this line, but later.

I was thinking if this would benefit us:

struct Options {
  Endpoint! string
  Token! string
  Client HttpClient
}

and since those are required, initializing Options without those fields would throw a compilation error:

x := Options {Endpoint: "something", Token: "token"} // would be okay
x := Options {Endpoint: "", Token: ""} // would be okay
x := Options {Endpoint: "something", Token: "token", Client: getClient()} // would be okay
x := Options {Endpoint: "something"} // would error compiling
x := Options {Endpoint: "something", Client: getClient()} // would still error while compiling

I understand this is a language change and could be solved using constructors, but adding those would mean we detect stuff early while compilation.

Personally I like if everything is required by default and use ? to say optional (like regex), but that'd break the whole golang ecosystem (and that'd be for golang 2), but introducing ! (or any other operator) shouldn't break anything, that I know of.

I heard there was a proposal for safe pointer which could never be nil, this is similar to that, but for struct fields, including string or int or any type.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeLanguageChangeSuggested changes to the Go languageProposalWaitingForInfoIssue is not actionable because of missing required information, which needs to be provided.v2An incompatible library change

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions