Initializing Structs
Part of the Fundamentals section of Coddy's GO journey — lesson 98 of 109.
There are multiple ways to initialize structs in Go. Let's explore the most common methods.
Create a struct with field names:
type Person struct {
name string
age int
}
func main() {
// Initialize with field names
person1 := Person{name: "Alice", age: 30}
fmt.Println(person1)
}The output shows our initialized struct:
{Alice 30}You can also initialize a struct without field names, but you must provide values in order:
person2 := Person{"Bob", 25}
fmt.Println(person2)Result:
{Bob 25}Create an empty struct with zero values:
person3 := Person{}
fmt.Println(person3)Result:
{ 0}Challenge
BeginnerIn this challenge, you'll practice initializing a struct in Go. We've defined a Person struct with fields for name, age, and whether the person is employed.
Your task is to initialize a new Person struct instance with the following information:
- Name: "Alice"
- Age: 28
- IsEmployed: true
Then we'll print out the information about this person.
Cheat sheet
There are multiple ways to initialize structs in Go:
Initialize with field names:
person1 := Person{name: "Alice", age: 30}Initialize without field names (values must be in order):
person2 := Person{"Bob", 25}Create empty struct with zero values:
person3 := Person{}Try it yourself
package main
import "fmt"
// Person struct definition
type Person struct {
Name string
Age int
IsEmployed bool
}
func main() {
// TODO: Initialize a Person struct with name "Alice", age 28, and isEmployed true
// Use either the field names or the struct literal syntax
var alice Person
// Print the person's information
fmt.Printf("Name: %s\n", alice.Name)
fmt.Printf("Age: %d\n", alice.Age)
fmt.Printf("Employed: %t\n", alice.IsEmployed)
}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 Actions10Composite Types: Arrays
Introduction to ArraysDeclaring ArraysInitializing ArraysAccessing Array ElementsArray Length with `len`Iterating Over ArraysMulti-dimensional Arrays13Composite Types: Structs
Defining Custom TypesCreating Struct InstancesAccessing Struct FieldsPointers to StructsInitializing StructsEmbedded StructsAnonymous StructsRecap - Custom Data Structures2Variables 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