Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion with "..." operator in golang

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.

like image 711
IhtkaS Avatar asked Feb 24 '15 09:02

IhtkaS


People also ask

What is a relational operator in Golang?

A relational operator is a symbol that tells the compiler to do a specific comparison of two values. There are the following operators available for relational operations on operands in Golang.

How do you assign a number to a variable in Golang?

Here, the = operator assigns the value on right ( 34) to the variable on left ( number ). In the above example, we have used the assignment operator to assign the value of the num variable to the result variable. In Go, we can also use an assignment operator together with an arithmetic operator.

What are the arithmetic operators in Golang?

Here's a complete list of Golang's arithmetic operators: Operator Description Example Result + Addition x + y Sum of x and y - Subtraction x - y Subtracts one value from another * Multiplication x * y Multiplies two values / Division x / y Quotient of x and y 3 more rows ...

How to use the modulo operator in Golang?

Note: The modulo operator is always used with integer values. In golang, we use ++ (increment) and -- (decrement) operators to increase and decrease the value of a variable by 1 respectively. For example, Note: We have used ++ and -- as prefixes (before variable).


1 Answers

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.

like image 100
icza Avatar answered Oct 18 '22 20:10

icza