How to use promoted fields in struct in Golang 1.20
In this video we are going to generate source code for the GoLang Program, How to use promoted fields in structs 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"
type Person struct {
name string
age int
}
type Employee struct {
Person // promoted field
salary int
}
func main() {
// create an instance of Employee struct
emp := Employee{
Person: Person{
name: "John",
age: 30,
},
salary: 50000,
}
// access the fields of Employee struct
fmt.Println("Employee name:", emp.name)
fmt.Println("Employee age:", emp.age)
fmt.Println("Employee salary:", emp.salary)
}
##############END OF SOURCE CODE#########################
Below is the explanation for the program:
In this program, we have defined two struct types: Person and Employee. The Employee struct includes a Person field, which is promoted. This means that the fields of the Person struct are accessible as if they were fields of the Employee struct.
In the main function, we create an instance of the Employee struct and initialize its fields. We can then access the fields of the Person struct using the dot notation on the Employee struct instance.
#go #goprogramming #golang #golangtutorial #golanguage