Declaring Slice Literals
Part of the Fundamentals section of Coddy's GO journey — lesson 75 of 109.
Slice literals let you create and initialize slices in a single step. They're similar to array literals but without specifying the size.
Create a slice of strings using a slice literal:
colors := []string{"red", "blue", "green"}
fmt.Println(colors)This displays:
[red blue green]You can also create an empty slice:
emptySlice := []int{}
fmt.Println(emptySlice, len(emptySlice))This displays:
[] 0Challenge
BeginnerIn this challenge, you'll practice creating a slice literal in Go. Slice literals allow you to create and initialize a slice in a single statement.
Your task is to create a slice literal containing the names of four colors: "red", "blue", "green", and "yellow".
Cheat sheet
Slice literals let you create and initialize slices in a single step, similar to array literals but without specifying the size.
Create a slice of strings using a slice literal:
colors := []string{"red", "blue", "green"}
fmt.Println(colors) // [red blue green]Create an empty slice:
emptySlice := []int{}
fmt.Println(emptySlice, len(emptySlice)) // [] 0Try it yourself
package main
import "fmt"
func main() {
// TODO: Create a slice literal named 'colors' containing the strings:
// "red", "blue", "green", and "yellow"
// Print the slice
fmt.Println("Colors:", colors)
// Print the length of the slice
fmt.Println("Number of colors:", len(colors))
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison Operators - Part 1Comparison Operators - Part 2Logical AND OperatorLogical OR OperatorLogical NOT OperatorOperator Precedence BasicsRecap - Making Comparisons7Control Flow: Loops
What The `for` Loop ExplainedFor Loop - BasicFor Loop - Condition OnlyThe `break` KeywordThe `continue` KeywordNested LoopsRecap - Repeating Actions2Variables and Basic Data Types
What is a variableType Inference with `:=`Integers (int)Floating-Point NumbersBooleansStringsZero ValuesConstantsNaming ConventionsRecap - Variables and Types5Basic Input/Output
Formatted OutputFormat VerbsPrinting TypesGetting Basic User InputRecap - Input and Output8Functions
Understanding FunctionsDeclaring a FunctionCalling FunctionsFunction ParametersReturning a Single ValueReturning Multiple ValuesNamed Return ValuesFunction Scope BasicsRecap - Creating Reusable Code3Basic Operators
Arithmetic OperatorsDivision OperatorThe Modulo OperatorAssignment OperatorAugmented Assignment OperatorsIncrement and DecrementRecap - Calculations6Control Flow: Conditionals
The `if` StatementThe `else` KeywordThe `else if` KeywordVariable Shadowing in `if`Initializing VariablesThe `switch` StatementSwitch with ExpressionsSwitch without ExpressionThe `fallthrough` KeywordRecap - Making Decisions