How to instantiate Struct using new keyword in Golang?


In Go, a struct is a composite data type that groups together zero or more values of different types. Structs can be created in several ways, including using the new keyword. In this article, we will discuss how to instantiate a struct using the new keyword in Go.

What is the new keyword in Go?

The new keyword in Go is a built-in function that allocates memory for a new value of a specified type and returns a pointer to it. The allocated memory is set to zero, which means that the new value will have its zero value for each field. The new function takes a single argument, which is the type of the value to allocate memory for.

Syntax for Instantiating a Struct Using new Keyword in Go

The syntax for instantiating a struct using the new keyword in Go is as follows −

var structPointer *StructType = new(StructType)

where StructType is the name of the struct type you want to instantiate, and structPointer is a pointer to the new struct value.

Example of Instantiating a Struct Using new Keyword in Go

Here's an example that demonstrates how to instantiate a struct using the new keyword in Go −

package main

import "fmt"

type Person struct {
   name string
   age  int
}

func main() {
   personPointer := new(Person)
   personPointer.name = "John Doe"
   personPointer.age = 30

   fmt.Printf("Name: %s\n", personPointer.name)
   fmt.Printf("Age: %d\n", personPointer.age)
}

Output

Name: John Doe
Age: 30

In this example, we define a Person struct with two fields: name and age. We then use the new keyword to allocate memory for a new Person value and return a pointer to it. Finally, we print the memory address of the new Person value using fmt.Println.

Conclusion

In this article, we discussed how to instantiate a struct using the new keyword in Go. The new keyword is a built-in function that allocates memory for a new value of a specified type and returns a pointer to it. We also provided an example that demonstrated how to use the new keyword to allocate memory for a new Person value. By following the syntax outlined in this article, you should be able to instantiate structs using the new keyword in Go.

Updated on: 08-May-2023

549 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements