Declaring Map Literals
Part of the Fundamentals section of Coddy's GO journey — lesson 85 of 109.
Map literals let you create and initialize maps in a single statement. They're similar to slice literals but require both key and value for each entry.
Create a map literal with string keys and integer values:
ages := map[string]int{
"Alice": 25,
"Bob": 30,
"Carol": 27,
}
fmt.Println(ages)Result:
map[Alice:25 Bob:30 Carol:27]You can also create an empty map literal:
emptyMap := map[string]int{}
fmt.Println(emptyMap)Result:
map[]Challenge
BeginnerIn this challenge, you'll practice creating a map literal in Go. Maps are collections of key-value pairs, similar to dictionaries in other languages.
Your task is to create a map literal that stores information about a few countries and their capitals. The map should have country names as keys (strings) and capital cities as values (also strings).
Try it yourself
package main
import "fmt"
func main() {
// TODO: Create a map literal called 'capitals' that maps countries to their capital cities
// Include at least these three pairs:
// "France" -> "Paris"
// "Japan" -> "Tokyo"
// "Brazil" -> "Brasilia"
// This will print out the map
fmt.Println(capitals)
// This will print out the capital of Japan
fmt.Println("The capital of Japan is:", capitals["Japan"])
}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