Structs and custom types are important concepts in Go that allow you to define your own data structures with specific fields and methods. Let's explore structs and custom types in detail, along with examples.
Structs in Go:
A struct is a composite data type that groups together zero or more fields with possibly different data types. It's used to represent a collection of related data.
Declaring and Using a Struct:
To declare a struct, define its fields and their types within a 'type'declaration.
type Person struct { FirstName string LastName string Age int }
You can create anonymous structs directly without defining a named type.
func main() {
person := struct {
Name string
Age int
}{
Name: "Alice",
Age: 25,
}
fmt.Println(person.Name, person.Age)
}
Custom Types:
Custom types in Go are type aliases or new type definitions created from existing types. They can improve code clarity and provide additional type safety.
Type Aliases:
Type aliases provide alternative names for existing types. They don't create new types, just new names.
type Celsius float64 type Fahrenheit float64
func main() { c := Celsius(25.0) fmt.Println(c) }
New Type Definitions:
New type definitions create distinct types with the same underlying type. This can help prevent mistakes in your code by distinguishing between different use cases.
type Age int
func main() { age := Age(30) fmt.Println(age) }
Custom Type with Methods:
You can define methods on your custom types, allowing you to associate behavior with the type.
Custom types include type aliases and new type definitions.
Type aliases provide alternative names for existing types.
New type definitions create distinct types with the same underlying type.
Methods can be associated with custom types, including pointer receivers.
By understanding how to create and use structs, along with custom types and their methods, you can create well-structured and efficient programs in Go. These concepts enhance code organization and readability, making your codebase more maintainable and extensible.