×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

How to instantiate struct using new keyword in Golang?

Learn about the structure in Golang, structure (struct) instantiation using the new keyword.
Submitted by IncludeHelp, on October 05, 2021

In the Go programming language (other programming languages such as C and C++) a structure (struct) is mainly used to create a customized type that can hold all other data types.

A struct can also be created by using the new keyword and the structure’s data can be accessed/manipulated by using the dot (.) operator.

Syntax:

structure_variable := new(structure_name)

Consider the below examples demonstrating the structure instantiation using the new keyword.

Example 1:

// Example structure instantiation
// using the new keyword

package main

import "fmt"

// structure
type student struct {
	name string
	roll int
	perc float32
}

func main() {
	std := new(student)
	std.name = "Alex"
	std.roll = 108
	std.perc = 84.8

	// Printing structure
	fmt.Println("std:", std)
	fmt.Println("Elements...")
	fmt.Println("Name:", std.name)
	fmt.Println("Roll Number:", std.roll)
	fmt.Println("Percentage:", std.perc)
}

Output:

std: &{Alex 108 84.8}
Elements...
Name: Alex
Roll Number: 108
Percentage: 84.8

Example 2:

// Example structure instantiation
// using the new keyword

package main

import "fmt"

// structure
type Address struct {
	name    string
	city    string
	pincode int
}

func main() {
	add1 := new(Address)
	add1.name = "Alex"
	add1.city = "New Delhi"
	add1.pincode = 110065

	add2 := new(Address)
	add2.name = "Alvin"
	add2.city = "Mumbai"
	add2.pincode = 400004

	// Printing structures
	fmt.Println("add1:", add1)
	fmt.Println("Elements...")
	fmt.Println("Name:", add1.name)
	fmt.Println("City:", add1.city)
	fmt.Println("Pincode:", add1.pincode)

	fmt.Println("add2:", add2)
	fmt.Println("Elements...")
	fmt.Println("Name:", add2.name)
	fmt.Println("City:", add2.city)
	fmt.Println("Pincode:", add2.pincode)
}

Output:

add1: &{Alex New Delhi 110065}
Elements...
Name: Alex
City: New Delhi
Pincode: 110065
add2: &{Alvin Mumbai 400004}
Elements...
Name: Alvin
City: Mumbai
Pincode: 400004

Golang FAQ »



Comments and Discussions!

Load comments ↻





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