Anonymous Structs
Part of the Object Oriented Programming section of Coddy's GO journey — lesson 15 of 107.
An anonymous struct is a struct without a named type. You define its structure and create an instance in one step, without using the type keyword.
person := struct {
Name string
Age int
}{
Name: "Alice",
Age: 30,
}This creates a struct value directly without declaring a reusable type. Anonymous structs are useful when you need a quick, one-off data structure that won't be used elsewhere in your code.
A common use case is grouping related data for a single function or test.
config := struct {
Host string
Port int
}{
Host: "localhost",
Port: 8080,
}
fmt.Println(config.Host) // localhostAnonymous structs are also popular in table-driven tests where each test case has unique fields.
tests := []struct {
input int
expected int
}{
{1, 2},
{5, 10},
}Since anonymous structs have no type name, you cannot define methods on them or reuse the type elsewhere. Use them for temporary, localized data grouping. For anything you'll reference multiple times, define a named struct type instead.
Challenge
EasyLet's build a quick configuration system that demonstrates when anonymous structs shine—for one-off data grouping that doesn't need a reusable type.
You'll organize your code across two files:
config.go: Create a function calledGetServerConfigthat takes a server name (string), port (int), and debug mode (bool) as parameters. This function should return an anonymous struct containing these three values as fields:Name,Port, andDebug. Since this configuration is only used in one place, there's no need to define a named type for it.main.go: Read the server configuration values from input, call yourGetServerConfigfunction, and display the configuration details.
The following inputs will be provided:
- Line 1: Server name
- Line 2: Port number
- Line 3: Debug mode (
trueorfalse)
Output format:
Server: [Name]
Port: [Port]
Debug: [Debug]For example, given api-server, 8080, and true, your output should be:
Server: api-server
Port: 8080
Debug: trueNotice how the anonymous struct lets you return grouped data without cluttering your codebase with a type that's only used once.
Cheat sheet
An anonymous struct is a struct without a named type, defined and instantiated in one step without using the type keyword:
person := struct {
Name string
Age int
}{
Name: "Alice",
Age: 30,
}Anonymous structs are useful for one-off data structures that won't be reused elsewhere in your code.
Common use cases include grouping related data for a single function:
config := struct {
Host string
Port int
}{
Host: "localhost",
Port: 8080,
}
fmt.Println(config.Host) // localhostAnd table-driven tests:
tests := []struct {
input int
expected int
}{
{1, 2},
{5, 10},
}Anonymous structs cannot have methods defined on them or be reused as a type. Use them for temporary, localized data grouping. For types referenced multiple times, define a named struct instead.
Functions can return anonymous structs:
func GetConfig() struct {
Name string
Port int
} {
return struct {
Name string
Port int
}{
Name: "server",
Port: 8080,
}
}Try it yourself
package main
import (
"fmt"
)
func main() {
// Read input values
var name string
var port int
var debug bool
fmt.Scanln(&name)
fmt.Scanln(&port)
fmt.Scanln(&debug)
// TODO: Call GetServerConfig with the input values
// and store the returned anonymous struct
// TODO: Print the configuration in the required format:
// Server: [Name]
// Port: [Port]
// Debug: [Debug]
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of Go OOP
External FilesGo Workspace & ModulesPackages & ImportsExported vs Unexported NamesIntroduction to OOP in GoStructs as ClassesDefining Methods on StructsPointer vs Value ReceiversStruct InitializationConstructor FunctionsRecap - Simple Calculator4Interfaces
Introduction to InterfacesImplicit ImplementationInterface as ContractEmpty Interface (any)Type AssertionType SwitchInterface CompositionStringer & Error InterfacesRecap - Shape Calculator7Encapsulation
Exported vs Unexported FieldsPackage-Level EncapsulationGetter & Setter MethodsInformation Hiding in GoRecap - Student Records10Generics (Go 1.18+)
Introduction to GenericsType ParametersType ConstraintsGeneric StructsGeneric Methods WorkaroundRecap - Generic Collection2Types & Structs Deep Dive
Basic & Composite TypesCustom Type DefinitionsStruct TagsAnonymous StructsNested StructsZero Values & DefaultsRecap - Contact Book5Composition Over Inheritance
Why Go Has No InheritanceStruct Embedding BasicsMethod PromotionEmbedding Multiple StructsEmbedding vs AggregationShadowing Embedded MethodsRecap - Employee Hierarchy8Error Handling & OOP
The error InterfaceCustom Error TypesError Wrapping (fmt.Errorf)Sentinel Errorserrors.Is() and errors.As()Panic, Defer, and RecoverRecap - File Parser3Pointers & Memory
Pointer Basics in GoPointers to StructsPass by Value vs ReferenceThe new() FunctionGarbage Collection in GoRecap - Linked List Builder6Polymorphism in Go
Polymorphism via InterfacesDuck Typing in GoInterface Satisfaction RulesPolymorphic CollectionsDependency InjectionRecap - Payment Processor9Concurrency & OOP
Goroutines BasicsChannels & CommunicationBuffered vs Unbuffered ChanSelect Statementsync.Mutex & sync.RWMutexsync.WaitGroupThread-Safe Struct DesignRecap - Worker Pool