Golang: What the heck is a composite literal?

Jul 28, 2017 · 2 min read

Disclaimer: I’m still a beginner. If notice any technical error, please kindly let me know. Thanks!

It has been a few days since I started learning Go. I’m now learning about data structures like Array and Slice, and came across this exercise:

* Create an ARRAY which holds 5 VALUES of TYPE int
* Assign VALUES to each index position.

Let’s forget the composite literal thing. On my very first attempt, I did something like this:

var myArray [5]int
for i := 0; i < len(myArray); i++ {
myArray[i] = 3

The first statement initializes an array, that holds 5 integers. First part of the exercise done!

The second statement loops through the array, and assigns the value “3” for each index. You can run the code here, producing the result:

[3 3 3 3 3]

Alright, looks like we managed to finish the exercise. But, what the heck is a composite literal? And why does it matter for this exercise?

It turns out, a composite literal is something that can make our lives easier when we want to assign values upon a variable initialization. If we wanted to fill an array with “3” (or any other combination of integers) upon its initialization, we could use the following code instead of doing a for statement:

myArray := [5]int{3, 3, 3, 3, 3} // Short syntax// ORvar myArray [5]int = [5]int{3, 3, 3, 3, 3} // Long syntax

As a beginner, you’re probably scratching your head trying to understand it. Let’s break it down, step-by-step:

var myArray [5]int

That code declares an array of size 5, that holds integers. That is, it holds 5 integers. And we’re assigning a value to that array:

 = [5]int{3, 3, 3, 3, 3}

That’s a composite literal, that evaluates to an array of size 5, with the values 3, 3, 3, 3, 3:

[3, 3, 3, 3, 3]

Basically we’re just filling an array upon initialization, without manually iterating through each index and setting a value. You’ve probably seen them in other programming languages:

$myArray = [3, 3, 3, 3, 3];

This was particularly interesting for me, because I always used composite literals in other programming languages, but never realized it was called a “composite literal”.

If you want to learn more about about it, the Go spec is an awesome resource:

Composite literals construct values for structs, arrays, slices, and maps and create a new value each time they are evaluated. They consist of the type of the literal followed by a brace-bound list of elements.

Keep learning! You’re doing a great job!


Written by


Mainly a back-end web developer, and a curious fish as well

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade