How to instantiate Struct using new keyword in Golang?
Last Updated :
17 May, 2020
A struct is mainly a holder for all other data types. By using a pointer to a struct we can easily manipulate/access the data assigned to a struct. We can instantiate Struct using the new keyword as well as using Pointer Address Operator in Golang as shown in the below example:
Example: Here, you can see we are instantiating a Struct using new keyword.
package main
import "fmt"
type emp struct {
name string
empid int
salary int
}
func main() {
emp1 := new (emp)
emp1.name = "XYZ"
emp1.empid = 1555
emp1.salary = 25000
fmt.Println(emp1)
var emp2 = new (emp)
emp2.name = "ABC"
emp2.salary = 35000
fmt.Println(emp2)
}
|
Output:
&{XYZ 1555 25000}
&{ABC 0 35000}
Share your thoughts in the comments
Please Login to comment...