Skip to content

proposal: spec: add const literals for reference types like structs, maps, and arrays #21130

@ghasemloo

Description

@ghasemloo

Summary:
I propose adding const literals for reference types. E.g.

const c = []string{"1", "2", "3"}

Background:
Having const structs and arrays and maps is very useful to make sure the value is not changed. This is specially for tests where you want to make sure the value you are passing to functions, the only way right now is to make a copy of the object explicitly. When passing a const to a function or over a chan or assigning it to a variable Go would make a copy.

Proposal:
Allow definition of constants of reference types like structs, maps, and arrays.

Impact:
No impact on existing code.

Discussion:
This can simplifies code.

Alternatives:

Alternative 1: use var definitions, do explicitly copy
Without a built-in DeepCopy standard function the developer has to write their own copy functions for each type. It is also likely to break if the language adds new basic types in future.
But even if we had a DeepCopy standard function one cannot be sure that some other part of code is not changing the value of the variable. This gets worse when the const has to be exported or when the packages consists of multiple files.

var c = []string{"1", "2", "3"}
.
.
.
v := cCopy(c)

Alternative 2: generator function
We can write functions that create the struct and return it. E.g.

func genC() []string { return []string{"1", "2", "3"} }
.
.
.
v := genC(c)

This leads to code with lots of functions just for creating values.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions