ADVERTISEMENT
ADVERTISEMENT

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

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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.