go type struct
Step 1: Declaring a Struct
In Go, a struct is a composite data type that allows you to group together zero or more values with different data types into a single entity. To declare a struct, you use the type
keyword followed by the name of the struct and the struct
keyword. Here is an example:
type Person struct {
name string
age int
}
In this example, we declared a struct named Person
with two fields: name
of type string
and age
of type int
. The fields are defined inside curly braces {}
.
Step 2: Creating an Instance of the Struct
Once you have declared a struct, you can create instances of it. To create an instance of a struct, you can use the var
keyword followed by the name of the variable, the struct type, and the new
keyword. Here is an example:
var p1 Person
In this example, we created an instance of the Person
struct named p1
. The var
keyword is used to declare a variable, and we specify the type as Person
.
Step 3: Assigning Values to Struct Fields
To assign values to the fields of a struct, you can use the dot notation. Here is an example:
p1.name = "John"
p1.age = 30
In this example, we assigned the value "John" to the name
field of the p1
instance and the value 30 to the age
field.
Step 4: Accessing Struct Fields
To access the values of the fields in a struct, you can again use the dot notation. Here is an example:
fmt.Println("Name:", p1.name)
fmt.Println("Age:", p1.age)
In this example, we accessed the values of the name
and age
fields of the p1
instance and printed them using the fmt.Println()
function.
Step 5: Struct Initialization
You can also initialize a struct with values directly at the time of declaration. Here is an example:
p2 := Person{
name: "Alice",
age: 25,
}
In this example, we created an instance of the Person
struct named p2
and initialized its name
field with the value "Alice" and its age
field with the value 25.
Step 6: Anonymous Structs
Go also allows you to define anonymous structs, which are structs without a defined name. Here is an example:
p3 := struct {
name string
age int
}{
name: "Bob",
age: 35,
}
In this example, we created an anonymous struct with the name
and age
fields and assigned values to them directly. The instance of the anonymous struct is named p3
.
These are the basic steps involved in creating and using structs in Go. Structs are a powerful feature of the language that allow you to organize and manipulate data effectively.