Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

Confusion with "..." operator in golang

Writer Sophia Terry

What is the difference between the following two syntaxes in go?

x := [...]int{ 1:1, 2:2 }
x := []int{ 1:1, 2:2 }

Go's document says "The notation ... specifies an array length equal to the maximum element index plus one". But both the above syntaxes gives same lenght (3).

Is there a name for this operator "..."? Didn't find a way to search this operator in google.

1

1 Answer

The first line creates an array using an array literal, its length computed automatically by the compiler. It is detailed in the Composite literals section of the Language Specification.

The notation ... specifies an array length equal to the maximum element index plus one.

Note: this is not to be confused with the ... used to specify variadic parameters or to pass slices as their values. It is detailed in the Function types section of the spec.

The second line uses a slice literal and will result in a slice. Note that under the hood an array will also be created, but that is opaque.

4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy