Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
keyword
struct
communitycreator

The new keyword in Golang

Vafa Batool

Overview

structs are user-defined data types and are used to store other data types such as variables of int or string type. Using the keyword new to initialize a struct in Golang gives the user more control over the values of the various fields inside the struct.

Usage

new returns a pointer to the struct. Each individual field inside the struct can then be accessed and its value can be initialized or manipulated.

Note: another way of instantiating a struct in Golang is by using the pointer address operator.

An example of the usage of the new keyword is shown below.

Example

package main
import "fmt"

// example struct declared 
type Person struct {
  name string 
  age int 
  gender string 
}


func main() {
    //new returns a pointer to an instance of Person struct 
    var person1 = new(Person)

    //setting values of the fields
    person1.name = "Anna"
    person1.age = 25
    person1.gender = "female"

    //printing person1
    fmt.Println(person1)
}

More uses of the new keyword

Although commonly used to initialize structs, the new keyword can be used for any user-defined type.

Let’s look at another example:

package main
import "fmt"

//a slice variable with type int declared 
type mySlice []int


func main() {
    //an instance of mySlice initialized using short variable declaration
    slice1 := new(mySlice)

    //adding data to slice1 by first creating a temporary variable
    tempSlice := append(*slice1, 1,2,3)
    slice1 = &tempSlice

    fmt.Println(slice1)
}

Explanation

  • In line 5, we create a custom data type. It is a slice with int data type.

  • In line 10, we initialize an instance of the type mySlice using the new keyword.

  • In lines 13-14, we add data to the slice1 variable by first creating a temporary variable. Directly trying to add data to slice1 using the built-in append function results in an error. Since new returns a pointer to the struct, the address of tempSlice is stored in slice1.

RELATED TAGS

golang
keyword
struct
communitycreator
RELATED COURSES

View all Courses

Keep Exploring