How to instantiate Struct using new keyword in Golang?
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.
// Golang program to show how to instantiate// Struct using the new keywordpackage main import "fmt" type emp struct { name string empid int salary int} func main() { // emp1 is a pointer to // an instance of emp // using new keyword emp1 := new(emp) emp1.name = "XYZ" emp1.empid = 1555 emp1.salary = 25000 fmt.Println(emp1) // emp2 is an instance of emp var emp2 = new(emp) emp2.name = "ABC" emp2.salary = 35000 fmt.Println(emp2)} |
Output:
&{XYZ 1555 25000}
&{ABC 0 35000}



.png)