×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang new() Function with Examples

Golang | new() Function: Here, we are going to learn about the built-in new() function with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 20, 2021 [Last updated : March 15, 2023]

new() Function

In the Go programming language, the new() is a built-in function that is used to allocate memory. The first argument is a type, not a value, and the value returned is a pointer to a newly allocated zero value of that type.

It accepts one parameter (Type) and returns the pointer of the Type.

Syntax

func new(Type) *Type

Parameter(s)

  • Type : The type.

Return Value

The return type of the new() function is *Type, it returns the pointer of the Type.

Example 1

// Golang program to demonstrate the
// example of new() function

package main

import (
	"fmt"
)

func main() {
	// Declaring int slices using
	// new() function
	a := new([10]int)
	b := new([50]int)[0:10]

	// Printing the type, length, capacity and value
	fmt.Printf("a - Type: %T, Length: %d, Capacity: %d, Value: %v\n",
		a, len(a), cap(a), a)
	fmt.Printf("b - Type: %T, Length: %d, Capacity: %d, Value: %v\n",
		b, len(b), cap(b), b)
}

Output

a - Type: *[10]int, Length: 10, Capacity: 10, Value: &[0 0 0 0 0 0 0 0 0 0]
b - Type: []int, Length: 10, Capacity: 50, Value: [0 0 0 0 0 0 0 0 0 0]

Example 2

// Golang program to demonstrate the
// example of new() function

package main

import (
	"fmt"
)

func main() {
	// Declaring int slice using
	// new() function
	a := new([50]int)[0:10]

	// Appending the values to the slice
	a = append(a, []int{10, 20, 30, 40, 50}...)

	// Printing the type, length, capacity and value
	fmt.Printf("a - Type: %T, Length: %d, Capacity: %d, Value: %v\n",
		a, len(a), cap(a), a)
}

Output

a - Type: []int, Length: 15, Capacity: 50, Value: [0 0 0 0 0 0 0 0 0 0 10 20 30 40 50]

Golang builtin Package »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.