Structs in Go
Structs
66
Structs in Go are composite data types that are used to group different types of variables together in order to create a single logical entity. Structs are similar to classes in other object-oriented programming languages, and they are used to create custom data types.
In Go, a struct is defined using the type
keyword followed by the name of the struct and its fields enclosed in curly braces.
Here's an example:
type Person struct { Name string Age int }
This defines a Person
struct with two fields: Name
and Age
.
We can create instances of this struct like so:
p1 := Person{Name: "John Smith", Age: 30}
We can then access the fields of this struct using dot notation:
fmt.Println(p1.Name, p1.Age) // Output: John Smith 30
Structs can be used in a variety of ways in Go. For example, they can be used to represent data from a database, to pass data between functions, or to create custom data types for use in a program. By grouping related data together into a single entity, structs allow us to write cleaner and more efficient code.
March 27, 2023