How to access and modify individual fields of struct in GoLang 1.20



How to access and modify individual fields of struct in GoLang 1.20

How to access and modify individual fields of struct in GoLang 1.20

In this video we are going to generate source code for the GoLang Program, How to access and modify individual fields in struct using chatGPT.
After generating we will verify and run the generated code.

Important note on source code: only source code that are acceptable by the youtube description box will be displayed.

##############SOURCE CODE#########################

package main

import “fmt”

// Define a struct type for a person
type Person struct {
name string
age int
address Address
}

// Define a struct type for an address
type Address struct {
street string
city string
state string
zip string
}

func main() {
// Create a new Person struct using named fields
myInfo := Person{
name: “John Doe”,
age: 30,
address: Address{
street: “123 Main St”,
city: “Anytown”,
state: “CA”,
zip: “12345”,
},
}

// Access individual fields of the struct
fmt.Println(“Name:”, myInfo.name)
fmt.Println(“Age:”, myInfo.age)
fmt.Println(“Street:”, myInfo.address.street)
fmt.Println(“City:”, myInfo.address.city)
fmt.Println(“State:”, myInfo.address.state)
fmt.Println(“ZIP Code:”, myInfo.address.zip)

// Modify the value of a field
myInfo.address.zip = “67890”
fmt.Println(“Modified ZIP Code:”, myInfo.address.zip)
}

Below is the explanation for the program:

In this program, we define two struct types: Person and Address.
The Person struct has three fields: name, age, and address, where address is another struct of type Address.
The Address struct has four fields: street, city, state, and zip.

We then create a new Person struct using named fields, where we specify the values for each of the fields using the field names.
We also create a new Address struct using a similar syntax, and assign it to the address field of the Person struct.

To access individual fields of the myInfo struct, we use the . (dot) operator followed by the name of the field we want to access.
For example, we can access the name field using myInfo.name, and the street field within the address struct using myInfo.address.street.

We can also modify the value of a field by assigning a new value to it.
In this program, we modify the value of the zip field within the address struct by assigning a new value to it using myInfo.address.zip = “67890”.

#go #goprogramming #golang #golangtutorial #golanguage