Open In App

How to instantiate Struct using new keyword in Golang?

Last Updated : 17 May, 2020
Like Article

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 keyword
package 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) = "XYZ"
    emp1.empid = 1555
    emp1.salary = 25000
    // emp2 is an instance of emp
    var emp2 = new(emp) = "ABC"
    emp2.salary = 35000


&{XYZ 1555 25000}
&{ABC 0 35000}

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads