Documentation
¶
Overview ¶
arrays_slices.go
channels.go
colors.go
context_examples.go
defer_panic_recover.go
embedding_composition.go
file_io.go
functions.go
goroutines.go
interfaces.go
io_examples.go
io_package_examples.go
ioutil_examples.go
json_serialization.go
maps.go
methods.go
os_examples.go
os_package_examples.go
package_system.go
pointers.go
reflection_examples.go
string_formatting.go
type_system.go
internal/value_reference_concepts.go
Index ¶
- Constants
- Variables
- func Blue(text string) string
- func Bold(text string) string
- func BoldText(text string) string
- func Code(text string) string
- func ColorExamples()
- func Cyan(text string) string
- func Dim(text string) string
- func ErrorText(text string) string
- func Filter[T any](slice []T, predicate func(T) bool) []T
- func Green(text string) string
- func Header(text string) string
- func InfoText(text string) string
- func Map[T, R any](slice []T, mapper func(T) R) []R
- func PrintShapeInfo(s ShapeInterface)
- func Purple(text string) string
- func Red(text string) string
- func Reduce[T, R any](slice []T, initial R, reducer func(R, T) R) R
- func RunArraySliceExamples()
- func RunArraySliceProfessionalExamples()
- func RunChannelExamples()
- func RunContextExamples()
- func RunDeferPanicRecoverExamples()
- func RunEmbeddingCompositionExamples()
- func RunErrorHandlingExamples()
- func RunFileIOExamples()
- func RunFunctionExamples()
- func RunGoroutineExamples()
- func RunIOExamples()
- func RunIOPackageExamples()
- func RunIOUtilExamples()
- func RunInterfaceExamples()
- func RunJSONSerializationExamples()
- func RunMapExamples()
- func RunMethodExamples()
- func RunOSExamples()
- func RunOSPackageExamples()
- func RunPackageSystemExamples()
- func RunPointerExamples()
- func RunReflectionExamples()
- func RunStringFormattingExamples()
- func RunStructureExamples()
- func RunStudentGradeExample()
- func RunTypeSystemDemo()
- func RunValueReferenceExamples()
- func SectionHeader(title string) string
- func SectionTitle(text string) string
- func Subtitle(text string) string
- func SuccessText(text string) string
- func WarningText(text string) string
- func Yellow(text string) string
- type APIService
- type Account
- type AccountID
- type AccountStatus
- type AccountUser
- type AddressStruct
- type Animal
- type AutoCar
- type AutoEngine
- type AutoMotorcycle
- type AutoTruck
- type AutoVehicle
- type BankAccount
- type BaseHandler
- type BigStruct
- type Bird
- type Calculator
- type Car
- type Cat
- type Circle
- type CircleStruct
- type CircularA
- type CircularB
- type CircularBuffer
- type ComponentA
- type ComponentB
- type ComponentC
- type Config
- type ConsoleWriter
- type Counter
- type Counter2
- type CountingWriter
- type CustomError
- type CustomTime
- type CustomValidationError
- type CustomWriter
- type DataValidator
- type DatabaseConfig
- type DatabaseError
- type DatabaseService
- type DemoAccount
- type DemoBank
- type DemoPerson
- type Dog
- type EmailAddr
- type Employee
- type EmployeeStruct
- type Engine
- type EnhancedNavigator
- type Error
- type Event
- type FileHandler
- type FileProcessor
- type FileWriter
- type IntelligentGPS
- type Item
- type JSONConfig
- type JSONProduct
- type JSONUser
- type LineNumberWriter
- type LogEntry
- type Logger
- type ManagerStruct
- type MultiWriter
- type MyInt
- type MyInteger
- type NavigationGPS
- type NetworkWriter
- type Order
- type PerformanceCar
- type Person
- type PersonStr
- type PersonStruct
- type PremiumCar
- type Product
- type ProductHandler
- type ProductStruct
- type Profile
- type ReadWriter
- type Reader
- type Rectangle
- type RectangleStruct
- type RepeatingReader
- type RequestData
- type SafeSlice
- type ServerConfig
- type Shape
- type ShapeInterface
- type SlidingWindow
- type Square
- type StringRenderer
- type StringType
- type Stringer
- type Student
- type SystemProduct
- type SystemUser
- type TempValue
- type TimestampedEntity
- type UppercaseReader
- type User
- type UserHandler
- type UserService
- type ValidationError
- type Validator
- type VehicleFleet
- type VehicleHonker
- type VehicleNavigator
- type VehicleStarter
- type VehicleWheels
- type Writer
- type Writer2
Constants ¶
const ( ColorReset = "\033[0m" ColorRed = "\033[31m" ColorGreen = "\033[32m" ColorYellow = "\033[33m" ColorBlue = "\033[34m" ColorPurple = "\033[35m" ColorCyan = "\033[36m" ColorWhite = "\033[37m" ColorBold = "\033[1m" ColorDim = "\033[2m" )
ANSI Color Codes
const ( BgRed = "\033[41m" BgGreen = "\033[42m" BgYellow = "\033[43m" BgBlue = "\033[44m" BgPurple = "\033[45m" BgCyan = "\033[46m" BgWhite = "\033[47m" )
Background Colors
const ( MaxRetries = 3 DefaultTimeout = 30 * time.Second )
Package-level constants
const CustomTimeFormat = "2006-01-02 15:04:05"
Variables ¶
var ( PackageVersion = "1.0.0" PackageAuthor = "Golang Developer" )
Package-level variables (exported)
Functions ¶
func RunArraySliceExamples ¶
func RunArraySliceExamples()
RunArraySliceExamples - main function to run all array and slice examples
func RunArraySliceProfessionalExamples ¶
func RunArraySliceProfessionalExamples()
RunArraySliceProfessionalExamples - main function to run all professional array and slice examples
func RunChannelExamples ¶
func RunChannelExamples()
RunChannelExamples - main function to run all channel examples
func RunContextExamples ¶
func RunContextExamples()
RunContextExamples - main function to run all context examples
func RunDeferPanicRecoverExamples ¶
func RunDeferPanicRecoverExamples()
RunDeferPanicRecoverExamples - main function to run all defer, panic, and recover examples
func RunEmbeddingCompositionExamples ¶
func RunEmbeddingCompositionExamples()
RunEmbeddingCompositionExamples - main function to run all embedding examples
func RunFileIOExamples ¶
func RunFileIOExamples()
RunFileIOExamples - main function to run all File I/O examples
func RunFunctionExamples ¶
func RunFunctionExamples()
RunFunctionExamples - main function to run all function examples
func RunGoroutineExamples ¶
func RunGoroutineExamples()
RunGoroutineExamples - main function to run all goroutine examples
func RunIOExamples ¶
func RunIOExamples()
RunIOExamples - main function to run all IO package examples
func RunIOPackageExamples ¶
func RunIOPackageExamples()
RunIOPackageExamples - main function to run all IO package examples
func RunIOUtilExamples ¶
func RunIOUtilExamples()
RunIOUtilExamples - main function to run all IO/ioutil package examples
func RunInterfaceExamples ¶
func RunInterfaceExamples()
RunInterfaceExamples - main function to run all interface examples
func RunJSONSerializationExamples ¶
func RunJSONSerializationExamples()
RunJSONSerializationExamples - main function to run all JSON serialization examples
func RunMethodExamples ¶
func RunMethodExamples()
RunMethodExamples - main function to run all method examples
func RunOSExamples ¶
func RunOSExamples()
RunOSExamples - main function to run all OS package examples
func RunOSPackageExamples ¶
func RunOSPackageExamples()
RunOSPackageExamples - main function to run all OS package examples
func RunPackageSystemExamples ¶
func RunPackageSystemExamples()
RunPackageSystemExamples - main function to run all package system examples
func RunPointerExamples ¶
func RunPointerExamples()
RunPointerExamples - main function to run all pointer examples
func RunReflectionExamples ¶
func RunReflectionExamples()
RunReflectionExamples - main function to run all reflection examples
func RunStringFormattingExamples ¶
func RunStringFormattingExamples()
RunStringFormattingExamples - main function to run all string formatting examples
func RunStructureExamples ¶
func RunStructureExamples()
Main function that demonstrates all concepts
func RunStudentGradeExample ¶
func RunStudentGradeExample()
RunStudentGradeExample - demonstrates real-world application
func RunTypeSystemDemo ¶
func RunTypeSystemDemo()
RunTypeSystemDemo - main function to run all type system examples
func RunValueReferenceExamples ¶
func RunValueReferenceExamples()
RunValueReferenceExamples - main function to run all value vs reference examples
func SectionHeader ¶
func SectionTitle ¶
Helper functions (you'll need to implement these or import them)
func WarningText ¶
Types ¶
type APIService ¶
type APIService struct {
// contains filtered or unexported fields
}
APIService simulates an API service
func (*APIService) GetProductPrices ¶
GetProductPrices simulates getting product prices from API
type AccountStatus ¶
type AccountStatus string
const ( StatusActive AccountStatus = "active" StatusInactive AccountStatus = "inactive" StatusPending AccountStatus = "pending" )
Constants with custom types
type AccountUser ¶
type AccountUser struct {
ID int `json:"id" validate:"required"`
Name string `json:"name" validate:"required,min=2"`
Email string `json:"email" validate:"required,email"`
Age int `json:"age" validate:"min=0,max=120"`
IsActive bool `json:"is_active"`
}
User represents a sample user struct for reflection examples
type AddressStruct ¶
Nested struct
type AutoCar ¶
type AutoCar struct {
AutoEngine // Embedded struct
VehicleWheels // Embedded struct
Brand string
Model string
Year int
// contains filtered or unexported fields
}
Struct embedding examples
type AutoEngine ¶
Base types for embedding examples
func (*AutoEngine) Status ¶
func (e *AutoEngine) Status() string
func (*AutoEngine) Stop ¶
func (e *AutoEngine) Stop() error
type AutoMotorcycle ¶
type AutoMotorcycle struct {
AutoEngine // Embedded struct
VehicleWheels // Embedded struct
Brand string
Model string
HasSidecar bool
}
func (*AutoMotorcycle) Honk ¶
func (m *AutoMotorcycle) Honk() string
func (*AutoMotorcycle) String ¶
func (m *AutoMotorcycle) String() string
type AutoTruck ¶
type AutoTruck struct {
AutoEngine // Embedded struct
VehicleWheels // Embedded struct
Brand string
Model string
PayloadKg int
}
type AutoVehicle ¶
type BankAccount ¶
type BankAccount struct {
// contains filtered or unexported fields
}
Advanced struct with constructor pattern
func NewBankAccount ¶
func NewBankAccount(owner string, initialBalance float64) *BankAccount
Constructor function
func (*BankAccount) Deposit ¶
func (ba *BankAccount) Deposit(amount float64) error
Methods for BankAccount
func (BankAccount) GetBalance ¶
func (ba BankAccount) GetBalance() float64
func (BankAccount) GetOwner ¶
func (ba BankAccount) GetOwner() string
func (*BankAccount) Withdraw ¶
func (ba *BankAccount) Withdraw(amount float64) error
type BaseHandler ¶
type BaseHandler struct {
// contains filtered or unexported fields
}
func (*BaseHandler) LogRequest ¶
func (bh *BaseHandler) LogRequest(method, path string)
Move these methods to package level
func (*BaseHandler) Uptime ¶
func (bh *BaseHandler) Uptime() time.Duration
type BigStruct ¶
type BigStruct struct {
Data [1000]int
}
Example 3: Value receiver for performance
func (BigStruct) ProcessData ¶
Value receiver - copies the entire struct
func (*BigStruct) ProcessDataEfficient ¶
Pointer receiver - more efficient for large structs
type Calculator ¶
type Calculator struct {
Result float64
}
Example 6: Method expressions and method values
func (*Calculator) Add ¶
func (c *Calculator) Add(x float64)
func (Calculator) GetResult ¶
func (c Calculator) GetResult() float64
func (*Calculator) Multiply ¶
func (c *Calculator) Multiply(x float64)
type Circle ¶
type Circle struct {
Radius float64
}
Additional example: Circle with methods
func (Circle) Circumference ¶
type CircleStruct ¶
type CircleStruct struct {
Radius float64
}
Circle struct implementing Shape interface
func (CircleStruct) Area ¶
func (c CircleStruct) Area() float64
func (CircleStruct) Perimeter ¶
func (c CircleStruct) Perimeter() float64
type CircularBuffer ¶
type CircularBuffer struct {
// contains filtered or unexported fields
}
Scenario 1: Buffer management for network operations
func NewCircularBuffer ¶
func NewCircularBuffer(size int) *CircularBuffer
func (*CircularBuffer) Read ¶
func (cb *CircularBuffer) Read(data []byte) int
func (*CircularBuffer) Write ¶
func (cb *CircularBuffer) Write(data []byte) int
type ComponentA ¶
type ComponentA struct {
Name string
}
func (ComponentA) GetName ¶
func (a ComponentA) GetName() string
Move these methods to package level
type ComponentB ¶
type ComponentB struct {
Name string
}
func (ComponentB) GetName ¶
func (b ComponentB) GetName() string
type ComponentC ¶
type ComponentC struct {
ComponentA
ComponentB
Name string // Resolves conflict
}
type Config ¶
type Config struct {
APIKey string `json:"api_key"`
Timeout int `json:"timeout"`
Debug bool `json:"debug"`
// contains filtered or unexported fields
}
Exported types
func (*Config) GetEndpoint ¶
type ConsoleWriter ¶
type ConsoleWriter struct{}
func (ConsoleWriter) Write ¶
func (cw ConsoleWriter) Write(data string) error
type Counter ¶
type Counter struct {
Count int
}
Example 2: Pointer receiver vs Value receiver
func (Counter) BrokenIncrement ¶
func (c Counter) BrokenIncrement()
This won't work as expected (doesn't modify original)
type Counter2 ¶
type Counter2 struct {
// contains filtered or unexported fields
}
Example 3: Mutex for protecting shared resources
type CountingWriter ¶
Custom Writer that counts characters
type CustomError ¶
func (CustomError) Error ¶
func (ce CustomError) Error() string
type CustomTime ¶
CustomTime wrapper for custom time marshaling
func (CustomTime) MarshalJSON ¶
func (ct CustomTime) MarshalJSON() ([]byte, error)
func (*CustomTime) UnmarshalJSON ¶
func (ct *CustomTime) UnmarshalJSON(data []byte) error
type CustomValidationError ¶
CustomValidationError - custom error type for validation errors
func (CustomValidationError) Error ¶
func (e CustomValidationError) Error() string
Error implements the error interface for CustomValidationError
type CustomWriter ¶
type CustomWriter struct {
// contains filtered or unexported fields
}
CustomWriter implements io.Writer interface
type DataValidator ¶
type DataValidator interface {
Validate() bool
}
type DatabaseConfig ¶
type DatabaseError ¶
func (*DatabaseError) Error ¶
func (e *DatabaseError) Error() string
func (*DatabaseError) Unwrap ¶
func (e *DatabaseError) Unwrap() error
type DatabaseService ¶
type DatabaseService struct {
// contains filtered or unexported fields
}
DatabaseService simulates a database service
type DemoAccount ¶
type DemoBank ¶
type DemoBank struct {
Name string
Accounts [3]DemoAccount // Fixed-size array
}
type DemoPerson ¶
type EmployeeStruct ¶
Struct for demonstrating different method types
func (EmployeeStruct) GetInfo ¶
func (e EmployeeStruct) GetInfo() string
Method with value receiver for reading data
func (*EmployeeStruct) GiveRaise ¶
func (e *EmployeeStruct) GiveRaise(percentage float64)
Method with pointer receiver for modifying data
type EnhancedNavigator ¶
type EnhancedNavigator interface {
VehicleNavigator // Embedded interface
}
Interface embedding example
type Event ¶
type Event struct {
ID int `json:"id"`
Title string `json:"title"`
StartTime CustomTime `json:"start_time"`
EndTime CustomTime `json:"end_time"`
}
Custom time format example
type FileHandler ¶
func (*FileHandler) Read ¶
func (fh *FileHandler) Read() (string, error)
func (*FileHandler) Write ¶
func (fh *FileHandler) Write(data string) error
type FileProcessor ¶
type FileProcessor struct {
// contains filtered or unexported fields
}
FileProcessor demonstrates various file processing patterns
func NewFileProcessor ¶
func NewFileProcessor(input, output string) *FileProcessor
func (*FileProcessor) ProcessLines ¶
func (fp *FileProcessor) ProcessLines(processor func(string) string) error
ProcessLines processes file line by line
type FileWriter ¶
type FileWriter struct {
Filename string
}
func (FileWriter) Write ¶
func (fw FileWriter) Write(data string) error
type IntelligentGPS ¶
type IntelligentGPS struct {
// contains filtered or unexported fields
}
func (*IntelligentGPS) GetRoute ¶
func (sg *IntelligentGPS) GetRoute() []string
func (*IntelligentGPS) SetDestination ¶
func (sg *IntelligentGPS) SetDestination(dest string) error
type JSONConfig ¶
type JSONConfig struct {
AppName string `json:"app_name"`
Version string `json:"version"`
Debug bool `json:"debug,omitempty"`
Database DatabaseConfig `json:"database"`
Features map[string]bool `json:"features"`
Servers []ServerConfig `json:"servers"`
Metadata map[string]string `json:"metadata,omitempty"`
}
Config struct with different tag options
type JSONProduct ¶
type JSONProduct struct {
ID int `json:"id"`
Name string `json:"name"`
Price float64 `json:"price"`
Currency string `json:"currency"`
InStock bool `json:"in_stock"`
Description string `json:"description"`
}
Product struct for custom marshaling example
func (JSONProduct) MarshalJSON ¶
func (p JSONProduct) MarshalJSON() ([]byte, error)
Custom JSON marshaling for Product
func (*JSONProduct) UnmarshalJSON ¶
func (p *JSONProduct) UnmarshalJSON(data []byte) error
Custom JSON unmarshaling for Product
type JSONUser ¶
type JSONUser struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"-"` // Exclude from JSON
Age int `json:"age,omitempty"` // Omit if empty
IsActive bool `json:"is_active"`
CreatedAt time.Time `json:"created_at"`
Profile *Profile `json:"profile,omitempty"` // Pointer to nested struct
}
User struct with various JSON tags
type LineNumberWriter ¶
type LineNumberWriter struct {
// contains filtered or unexported fields
}
type ManagerStruct ¶
type ManagerStruct struct {
EmployeeStruct // embedded struct
Department string
Subordinates []string
}
Struct with embedded type
func (ManagerStruct) GetFullInfo ¶
func (m ManagerStruct) GetFullInfo() string
Method for embedded struct
type MultiWriter ¶
type MultiWriter struct {
// contains filtered or unexported fields
}
MultiWriter writes to multiple writers simultaneously
func NewMultiWriter ¶
func NewMultiWriter(writers ...io.Writer) *MultiWriter
type NavigationGPS ¶
type NavigationGPS struct {
}
func (*NavigationGPS) Enable ¶
func (g *NavigationGPS) Enable()
func (*NavigationGPS) GetLocation ¶
func (g *NavigationGPS) GetLocation() (float64, float64)
func (*NavigationGPS) Navigate ¶
func (g *NavigationGPS) Navigate(destination string) error
type NetworkWriter ¶
type NetworkWriter struct {
URL string
}
func (NetworkWriter) Write ¶
func (nw NetworkWriter) Write(data string) error
type PerformanceCar ¶
type PerformanceCar struct {
AutoCar
// contains filtered or unexported fields
}
Method shadowing example
func (*PerformanceCar) EnableTurbo ¶
func (sc *PerformanceCar) EnableTurbo()
func (*PerformanceCar) Start ¶
func (sc *PerformanceCar) Start() error
type PersonStruct ¶
type PersonStruct struct {
Name string
Age int
Email string
Address AddressStruct // embedded struct
}
Basic struct definition
type PremiumCar ¶
type PremiumCar struct {
AutoCar // Embedded struct
IntelligentGPS // Embedded struct (overrides Car's GPS)
// contains filtered or unexported fields
}
Complex embedding example
func (*PremiumCar) EnableLuxuryFeatures ¶
func (lc *PremiumCar) EnableLuxuryFeatures()
func (*PremiumCar) String ¶
func (lc *PremiumCar) String() string
type Product ¶
type Product struct {
Name string `json:"name"`
Price float64 `json:"price"`
Category string `json:"category"`
}
Product represents a sample product struct
type ProductHandler ¶
type ProductHandler struct {
BaseHandler // Embedded common functionality
// contains filtered or unexported fields
}
func (*ProductHandler) GetProduct ¶
func (ph *ProductHandler) GetProduct(id int) string
type ProductStruct ¶
type ProductStruct struct {
ID int `json:"id"`
Name string `json:"name"`
Price float64 `json:"price"`
Category string `json:"category"`
IsAvailable bool `json:"is_available"`
}
Bonus: Struct tags example (commonly used with JSON)
func (ProductStruct) FormattedName ¶
func (p ProductStruct) FormattedName() string
Method to format product name
func (ProductStruct) String ¶
func (p ProductStruct) String() string
type Profile ¶
type Profile struct {
Bio string `json:"bio"`
Website string `json:"website,omitempty"`
Interests []string `json:"interests"`
}
Profile nested struct
type ReadWriter ¶
type RectangleStruct ¶
Struct with methods
func (RectangleStruct) Dimensions ¶
func (r RectangleStruct) Dimensions() (float64, float64)
Method that returns multiple values
func (RectangleStruct) Perimeter ¶
func (r RectangleStruct) Perimeter() float64
Rectangle implementing Shape interface
func (*RectangleStruct) Scale ¶
func (r *RectangleStruct) Scale(factor float64)
Pointer receiver method
type RepeatingReader ¶
type RepeatingReader struct {
// contains filtered or unexported fields
}
Custom Reader that repeats a string
type RequestData ¶
RequestData represents data passed through context
type SafeSlice ¶
type SafeSlice[T any] struct { // contains filtered or unexported fields }
Thread-safe slice operations
func NewSafeSlice ¶
type ServerConfig ¶
type ShapeInterface ¶
Interface demonstration
type SlidingWindow ¶
type SlidingWindow struct {
// contains filtered or unexported fields
}
Scenario 2: Event processing with sliding window
func NewSlidingWindow ¶
func NewSlidingWindow(windowSize time.Duration, maxEvents int) *SlidingWindow
func (*SlidingWindow) AddEvent ¶
func (sw *SlidingWindow) AddEvent() bool
func (*SlidingWindow) CurrentCount ¶
func (sw *SlidingWindow) CurrentCount() int
type StringType ¶
type StringType = string
type SystemProduct ¶
type SystemProduct struct {
TimestampedEntity // Good: reusable pattern
ID int
Name string
Price float64
}
type SystemUser ¶
type SystemUser struct {
TimestampedEntity // Good: common behavior
ID int
Name string
Email string
}
type TimestampedEntity ¶
func (*TimestampedEntity) Touch ¶
func (te *TimestampedEntity) Touch()
type UppercaseReader ¶
type UppercaseReader struct {
// contains filtered or unexported fields
}
type UserHandler ¶
type UserHandler struct {
BaseHandler // Embedded common functionality
// contains filtered or unexported fields
}
func (*UserHandler) GetUser ¶
func (uh *UserHandler) GetUser(id int) string
type UserService ¶
type UserService struct{}
func (*UserService) CreateUser ¶
func (s *UserService) CreateUser(name, email string, age int) (*User, error)
type ValidationError ¶
Custom error types for advanced examples
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
type Validator ¶
type Validator interface {
Validate() error
}
Validator interface for custom validation
type VehicleFleet ¶
type VehicleFleet struct {
// contains filtered or unexported fields
}
Composition vs Embedding
func (*VehicleFleet) AddVehicle ¶
func (f *VehicleFleet) AddVehicle(v AutoVehicle)
func (*VehicleFleet) StartAll ¶
func (f *VehicleFleet) StartAll()
type VehicleHonker ¶
type VehicleHonker interface {
Honk() string
}
type VehicleNavigator ¶
type VehicleNavigator interface {
}
type VehicleStarter ¶
Interface definitions
type VehicleWheels ¶
func (*VehicleWheels) Description ¶
func (w *VehicleWheels) Description() string
Source Files
¶
- arrays_slices.go
- arrays_slices_professional.go
- channels.go
- colors.go
- context.go
- defer_panic_recover.go
- embedding_composition.go
- errors.go
- file_io.go
- functions.go
- goroutines.go
- interfaces.go
- io_examples.go
- io_package.go
- ioutil_examples.go
- json_serialization.go
- maps.go
- methods.go
- os_examples.go
- os_package.go
- package_system.go
- pointers.go
- reflection.go
- string_formatting.go
- structs.go
- type_system.go
- value_reference_concepts.go