Monday, 6 May 2019

Go Language: Structs


‘type’ keyword is used to create a new custom type.

Example
type Employee struct{
         name string
         id int
}

Above statements create a structure of type Employee. Employee structure contains two fields (name is of type string, id is of type int).

How to create an object of type Employee?
emp1 := Employee{}

Above statement creates an object of type Employee.

How can you access the fields (name, id) of structre Employee?
You can access the fields of Employee using ‘.’ Operator.

emp1.name = "Krishna"
emp1.id = 1

HelloWorld.go
package main

import "fmt"

func main() {
 emp1 := Employee{}

 emp1.name = "Krishna"
 emp1.id = 1

 fmt.Println("name : ", emp1.name)
 fmt.Println("id : ", emp1.id)
}


type Employee struct{
 name string
 id int
}

Output
name :  Krishna
id :  1

Creating an object using literal notation
You can even create an object to a structure using literal notation like below.

emp1 := Employee{"Krishna", 1}


HelloWorld.go
package main

import "fmt"

func main() {
 emp1 := Employee{"Krishna", 1}

 fmt.Println("name : ", emp1.name)
 fmt.Println("id : ", emp1.id)
}


type Employee struct{
 name string
 id int
}

One thing to notify here is that, this way of creating object, creates an object in local execution stack. But in most of the cases, creation of large object in heap is effective.

How can you create an object in heap?
You can create an object in heap using ‘new’ operator.

Syntax
objectName := new(StructureName)

Example
emp1 := new(Employee)


HelloWorld.go

package main

import "fmt"

func main() {
 emp1 := new(Employee)

 emp1.name = "Krishna"
 emp1.id = 1

 fmt.Println("name : ", emp1.name)
 fmt.Println("id : ", emp1.id)
}

type Employee struct{
 name string
 id int
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment