Saturday 4 September 2021

Go Struct

 In Go, Struct can be used to create user-defined types.

Struct is a composite type means it can have different properties and each property can have their own type and value.

Struct can represent real-world entity with these properties. We can access a property data as a single entity. It is also valued types and can be constructed with the new() function.

Go Struct Example

  1. package main  
  2. import (  
  3.    "fmt"  
  4. )  
  5. type person struct {  
  6.    firstName string  
  7.    lastName  string  
  8.    age       int  
  9. }  
  10. func main() {  
  11.    x := person{age: 30, firstName: "John", lastName: "Anderson", }  
  12.    fmt.Println(x)  
  13.    fmt.Println(x.firstName)  
  14. }  

Output:

{John Anderson 30}
John

Go Embedded Struct

Struct is a data type and can be used as an anonymous field (having only the type). One struct can be inserted or "embedded" into other struct.

It is a simple 'inheritance' which can be used to implement implementations from other type or types.

Go Embedded Struct Example

  1. package main  
  2. import (  
  3.    "fmt"  
  4. )  
  5. type person struct {  
  6.    fname string  
  7.    lname string}  
  8. type employee struct {  
  9.    person  
  10.    empId int  
  11. }  
  12. func (p person) details() {  
  13.    fmt.Println(p, " "+" I am a person")  
  14. }  
  15. func (e employee) details() {  
  16.    fmt.Println(e, " "+"I am a employee")  
  17. }  
  18. func main() {  
  19.    p1 := person{"Raj""Kumar"}  
  20.    p1.details()  
  21.    e1 := employee{person:person{"John""Ponting"}, empId: 11}  
  22.    e1.details()  
  23. }  

Output:

{Raj Kumar}   I am a person
{{John Ponting} 11}  I am a employee


No comments:

Post a Comment