Custom Types and Structs in Go
In Go, you can define your own types and create complex data structures using structs.
Custom Types
A custom type is defined using the type
keyword. It can be based on existing types:
1type UserID int
Structs
A struct is a collection of fields. It’s used to group data together to form records.
Defining Structs
Use the type
keyword followed by the struct name and the keyword struct
:
1type Person struct {
2 Name string
3 Age int
4}
Using Structs
To create an instance of a struct, use the struct name followed by field values:
1p := Person{Name: "Alice", Age: 30}
Methods on Structs
You can define methods on structs:
1func (p Person) Greet() string {
2 return "Hello, my name is " + p.Name
3}
Conclusion
Custom types and structs are powerful features in Go that allow you to define complex data types and structures, making your code more organized and expressive.
1
Enter to Rename, Shift+Enter to Preview