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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
    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)
}

chevron_right


Output:

&{XYZ 1555 25000}
&{ABC 0 35000}
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.