Monday 6 May 2019

Go Language: Construct an object to a structure using &


You can even create an object to a structure using & operator.

Example
emp1 := &Employee{}

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

You can use literal notation while constructing the object using &.

Example
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
}

Output
name :  Krishna

id :  1



Previous                                                 Next                                                 Home

No comments:

Post a Comment