Skip to content

proposal: Go 2: allow literal values without preceding literal types #24414

Closed
@pcostanza

Description

@pcostanza

In many cases, it is already clear from the context what type a literal value should be, so it would be convenient to allow for dropping the requirement to explicitly repeat the literal type. For example, in the following code, currently the literal type has to be repeated.

var v someStruct
v = someStruct{x: 1, y: 2, z: 3}

This proposal suggests that the last line could be written as follows:

v = {x: 1, y: 2, z: 3}

This in itself is not a major improvement for such simple cases. However, a particular use case I have in mind that this would enable is what in other languages is provided through keyword parameters. Here is an example to illustrate the use case:

func FormatFloat(f float64, opt struct {fmt byte; prec, bitSize int;}) string {
   fmt := byte(‘g’) // default value
   if opt.fmt != 0 {
      fmt = opt.fmt
   }
   prec := -1 // default value
   if opt.prec != 0 {
      prec = op.prec
   }
   bitSize = 64 // default value
   if opt.bitSize != 0 {
      bitSize = opt.bitSize
   }
   return strconv.FormatFloat(f, fmt, prec, bitSize)
}

In this example, checks against default 0 values are included to test whether a ‘keyword’ parameter was provided at the call site or not. This function can now be used as follows:

FormatFloat(3.14, {}) // use default options
FormatFloat(2.78, {fmt: ‘e’, bitSize: 32}) // deviate from some default options

Keyword parameters are very useful in other languages (IMHO), and dropping literal types from literal values if the context allows for it would add something very close without adding any extra features to the language.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions