internal

package
v0.0.0-...-e8f66ea Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 15, 2025 License: MIT Imports: 26 Imported by: 0

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

View Source
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

View Source
const (
	BgRed    = "\033[41m"
	BgGreen  = "\033[42m"
	BgYellow = "\033[43m"
	BgBlue   = "\033[44m"
	BgPurple = "\033[45m"
	BgCyan   = "\033[46m"
	BgWhite  = "\033[47m"
)

Background Colors

View Source
const (
	MaxRetries     = 3
	DefaultTimeout = 30 * time.Second
)

Package-level constants

View Source
const CustomTimeFormat = "2006-01-02 15:04:05"

Variables

View Source
var (
	PackageVersion = "1.0.0"
	PackageAuthor  = "Golang Developer"
)

Package-level variables (exported)

Functions

func Blue

func Blue(text string) string

func Bold

func Bold(text string) string

func BoldText

func BoldText(text string) string

func Code

func Code(text string) string

func ColorExamples

func ColorExamples()

Example usage function

func Cyan

func Cyan(text string) string

func Dim

func Dim(text string) string

func ErrorText

func ErrorText(text string) string

func Filter

func Filter[T any](slice []T, predicate func(T) bool) []T

Generic slice utility functions (Go 1.18+)

func Green

func Green(text string) string
func Header(text string) string

Enhanced formatting

func InfoText

func InfoText(text string) string

func Map

func Map[T, R any](slice []T, mapper func(T) R) []R

func PrintShapeInfo

func PrintShapeInfo(s ShapeInterface)

Function that works with interface

func Purple

func Purple(text string) string

func Red

func Red(text string) string

Helper Functions

func Reduce

func Reduce[T, R any](slice []T, initial R, reducer func(R, T) R) R

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 RunErrorHandlingExamples

func RunErrorHandlingExamples()

Main function to run all 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 RunMapExamples

func RunMapExamples()

RunMapExamples - main function to run all map 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 SectionHeader(title string) string

func SectionTitle

func SectionTitle(text string) string

Helper functions (you'll need to implement these or import them)

func Subtitle

func Subtitle(text string) string

func SuccessText

func SuccessText(text string) string

Success, Warning, Error functions

func WarningText

func WarningText(text string) string

func Yellow

func Yellow(text string) string

Types

type APIService

type APIService struct {
	// contains filtered or unexported fields
}

APIService simulates an API service

func (*APIService) GetProductPrices

func (api *APIService) GetProductPrices(ctx context.Context, products []string) ([]float64, error)

GetProductPrices simulates getting product prices from API

type Account

type Account struct {
	ID    AccountID
	Email EmailAddr
	Name  string
}

Struct types

func (Account) String

func (a Account) String() string

func (Account) Validate

func (a Account) Validate() bool

type AccountID

type AccountID int

Custom types based on built-in types

func (AccountID) String

func (a AccountID) String() string

Method on custom type

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

type AddressStruct struct {
	Street  string
	City    string
	Country string
}

Nested struct

type Animal

type Animal interface {
	Speak() string
	Move() string
}

Example 6: Polymorphism with interfaces

type AutoCar

type AutoCar struct {
	AutoEngine    // Embedded struct
	VehicleWheels // Embedded struct
	NavigationGPS // Embedded struct
	Brand         string
	Model         string
	Year          int
	// contains filtered or unexported fields
}

Struct embedding examples

func (*AutoCar) Honk

func (c *AutoCar) Honk() string

Additional methods for embedded types

func (*AutoCar) String

func (c *AutoCar) String() string

type AutoEngine

type AutoEngine struct {
	Horsepower int
	Fuel       string
	Running    bool
}

Base types for embedding examples

func (*AutoEngine) Start

func (e *AutoEngine) Start() error

Methods for base types

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
	NavigationGPS // Embedded struct
	Brand         string
	Model         string
	PayloadKg     int
}

func (*AutoTruck) Honk

func (t *AutoTruck) Honk() string

func (*AutoTruck) LoadCargo

func (t *AutoTruck) LoadCargo(weight int) error

func (*AutoTruck) String

func (t *AutoTruck) String() string

type AutoVehicle

type AutoVehicle interface {
	Start() error
	Stop() error
	String() string
}

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

func (b BigStruct) ProcessData() int

Value receiver - copies the entire struct

func (*BigStruct) ProcessDataEfficient

func (b *BigStruct) ProcessDataEfficient() int

Pointer receiver - more efficient for large structs

type Bird

type Bird struct {
	Name string
}

func (Bird) Move

func (b Bird) Move() string

func (Bird) Speak

func (b Bird) Speak() string

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 Car

type Car struct {
	Brand  string
	Model  string
	Engine // Embedded struct
}

func (Car) Drive

func (c Car) Drive()

func (Car) Start

func (c Car) Start()

Method can be overridden

type Cat

type Cat struct {
	Name string
}

func (Cat) Move

func (c Cat) Move() string

func (Cat) Speak

func (c Cat) Speak() string

type Circle

type Circle struct {
	Radius float64
}

Additional example: Circle with methods

func (Circle) Area

func (c Circle) Area() float64

func (Circle) Circumference

func (c Circle) Circumference() float64

func (Circle) String

func (c Circle) String() string

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 CircularA

type CircularA struct {
	B *CircularB `json:"b"`
}

type CircularB

type CircularB struct {
	A *CircularA `json:"a"`
}

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 NewConfig

func NewConfig() *Config

Exported functions

func (*Config) GetEndpoint

func (c *Config) GetEndpoint() string

func (*Config) SetAPIKey

func (c *Config) SetAPIKey(key string)

Exported methods

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)

func (Counter) GetCount

func (c Counter) GetCount() int

Value receiver - works with a copy

func (*Counter) Increment

func (c *Counter) Increment()

Pointer receiver - modifies the original

type Counter2

type Counter2 struct {
	// contains filtered or unexported fields
}

Example 3: Mutex for protecting shared resources

func (*Counter2) GetValue

func (c *Counter2) GetValue() int

func (*Counter2) Increment

func (c *Counter2) Increment()

type CountingWriter

type CountingWriter struct {
	CharCount  map[rune]int
	TotalBytes int
}

Custom Writer that counts characters

func (*CountingWriter) Write

func (w *CountingWriter) Write(p []byte) (n int, err error)

type CustomError

type CustomError struct {
	Code    int
	Message string
}

func (CustomError) Error

func (ce CustomError) Error() string

type CustomTime

type CustomTime struct {
	time.Time
}

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

type CustomValidationError struct {
	Field   string
	Message string
}

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

func (CustomWriter) Write

func (cw CustomWriter) Write(p []byte) (n int, err error)

type DataValidator

type DataValidator interface {
	Validate() bool
}

type DatabaseConfig

type DatabaseConfig struct {
	Host     string `json:"host"`
	Port     int    `json:"port"`
	Username string `json:"username"`
	Password string `json:"-"` // Never include in JSON
	SSL      bool   `json:"ssl"`
}

type DatabaseError

type DatabaseError struct {
	Operation string
	Table     string
	Err       error
}

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

func (*DatabaseService) GetUser

func (db *DatabaseService) GetUser(ctx context.Context, userID string) (string, error)

GetUser simulates getting user from database

func (*DatabaseService) SaveOrder

func (db *DatabaseService) SaveOrder(ctx context.Context, order *Order) error

SaveOrder simulates saving order to database

type DemoAccount

type DemoAccount struct {
	AccountID string
	Funds     float64
}

type DemoBank

type DemoBank struct {
	Name     string
	Accounts [3]DemoAccount // Fixed-size array
}

type DemoPerson

type DemoPerson struct {
	Name string
	Age  int
}

type Dog

type Dog struct {
	Name string
}

func (Dog) Move

func (d Dog) Move() string

func (Dog) Speak

func (d Dog) Speak() string

type EmailAddr

type EmailAddr string

func (EmailAddr) String

func (e EmailAddr) String() string

func (EmailAddr) Validate

func (e EmailAddr) Validate() bool

type Employee

type Employee struct {
	ID       int
	Name     string
	Position string
	Salary   float64
}

Employee - struct for map examples

type EmployeeStruct

type EmployeeStruct struct {
	ID       int
	Name     string
	Position string
	Salary   float64
}

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

func (EmployeeStruct) IsValid

func (e EmployeeStruct) IsValid() bool

Method that validates data

type Engine

type Engine struct {
	Power int
}

Example 5: Embedded methods

func (Engine) Start

func (e Engine) Start()

func (Engine) Stop

func (e Engine) Stop()

type EnhancedNavigator

type EnhancedNavigator interface {
	VehicleNavigator // Embedded interface
	SetDestination(string) error
	GetRoute() []string
}

Interface embedding example

type Error

type Error interface {
	Error() string
}

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

type FileHandler struct {
	Filename string
	Data     string
}

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 {
	NavigationGPS // Embedded 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 Item

type Item struct {
	ID    int
	Name  string
	Price float64
}

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
}

func (*LineNumberWriter) Write

func (lnw *LineNumberWriter) Write(p []byte) (n int, err error)

type LogEntry

type LogEntry struct {
	Timestamp time.Time
	Level     string
	Message   string
}

LogEntry represents a log entry structure

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

func NewLogger

func NewLogger(prefix string) *Logger

func (*Logger) Debug

func (l *Logger) Debug(message string)

func (*Logger) Log

func (l *Logger) Log(message string)

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

func (*MultiWriter) Write

func (mw *MultiWriter) Write(p []byte) (n int, err error)

type MyInt

type MyInt int

Example 4: Method sets

func (*MyInt) Double

func (m *MyInt) Double()

func (MyInt) String

func (m MyInt) String() string

type MyInteger

type MyInteger = int

Type aliases (Go 1.9+)

type NavigationGPS struct {
	Latitude  float64
	Longitude float64
	Enabled   bool
}
func (g *NavigationGPS) Enable()
func (g *NavigationGPS) GetLocation() (float64, float64)
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 Order

type Order struct {
	ID       string
	UserID   string
	Products []string
	Total    float64
}

Order represents an order

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 Person

type Person struct {
	Name string
	Age  int
}

Example 3: Pointer to struct

type PersonStr

type PersonStr struct {
	Name string
	Age  int
}

Person - struct for sorting example

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 ReadWriter interface {
	Reader
	Writer2
}

type Reader

type Reader interface {
	Read() (string, error)
}

Example 5: Interface composition

type Rectangle

type Rectangle struct {
	Width  float64
	Height float64
}

Example 1: Basic methods

func (Rectangle) Area

func (r Rectangle) Area() float64

func (Rectangle) Perimeter

func (r Rectangle) Perimeter() float64

func (Rectangle) String

func (r Rectangle) String() string

type RectangleStruct

type RectangleStruct struct {
	Width  float64
	Height float64
}

Struct with methods

func (RectangleStruct) Area

func (r RectangleStruct) Area() float64

Value receiver method

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

func (*RepeatingReader) Read

func (r *RepeatingReader) Read(p []byte) (n int, err error)

type RequestData

type RequestData struct {
	UserID    string
	RequestID string
	IP        string
}

RequestData represents data passed through context

type SafeSlice

type SafeSlice[T any] struct {
	// contains filtered or unexported fields
}

Thread-safe slice operations

func NewSafeSlice

func NewSafeSlice[T any]() *SafeSlice[T]

func (*SafeSlice[T]) Append

func (s *SafeSlice[T]) Append(item T)

func (*SafeSlice[T]) Get

func (s *SafeSlice[T]) Get(index int) (T, bool)

func (*SafeSlice[T]) Len

func (s *SafeSlice[T]) Len() int

func (*SafeSlice[T]) ToSlice

func (s *SafeSlice[T]) ToSlice() []T

type ServerConfig

type ServerConfig struct {
	Name   string `json:"name"`
	Host   string `json:"host"`
	Port   int    `json:"port"`
	Weight int    `json:"weight,omitempty"`
}

type Shape

type Shape interface {
	Area() float64
	Perimeter() float64
}

Example 1: Basic interface

type ShapeInterface

type ShapeInterface interface {
	Area() float64
	Perimeter() float64
}

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 Square

type Square struct {
	Side float64
}

func (Square) Area

func (s Square) Area() float64

func (Square) Perimeter

func (s Square) Perimeter() float64

type StringRenderer

type StringRenderer interface {
	String() string
}

Interface types

type StringType

type StringType = string

type Stringer

type Stringer interface {
	String() string
}

Additional interfaces for demonstration

type Student

type Student struct {
	Name   string
	Grades [5]int
}

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 TempValue

type TempValue float64

func (TempValue) Celsius

func (t TempValue) Celsius() float64

func (TempValue) Fahrenheit

func (t TempValue) Fahrenheit() float64

func (TempValue) String

func (t TempValue) String() string

type TimestampedEntity

type TimestampedEntity struct {
	CreatedAt time.Time
	UpdatedAt time.Time
}

func (*TimestampedEntity) Touch

func (te *TimestampedEntity) Touch()

type UppercaseReader

type UppercaseReader struct {
	// contains filtered or unexported fields
}

func (*UppercaseReader) Read

func (ur *UppercaseReader) Read(p []byte) (n int, err error)

type User

type User struct {
	ID    int
	Name  string
	Email string
	Age   int
}

User struct for examples

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

type ValidationError struct {
	Field   string
	Message string
	Code    int
}

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 {
	Navigate(destination string) error
	GetLocation() (float64, float64)
}

type VehicleStarter

type VehicleStarter interface {
	Start() error
	Stop() error
}

Interface definitions

type VehicleWheels

type VehicleWheels struct {
	Count int
	Size  string
}

func (*VehicleWheels) Description

func (w *VehicleWheels) Description() string

type Writer

type Writer interface {
	Write(data string) error
}

Example 2: Multiple types implementing same interface

type Writer2

type Writer2 interface {
	Write(data string) error
}