ADVERTISEMENT
ADVERTISEMENT

How to instantiate struct pointer address operator in Golang?

Learn about the structure in Golang, and how to instantiate struct pointer address operator in Golang?
Submitted by IncludeHelp, on October 06, 2021

In the Go programming language (as well as other programming languages like C and C++), the pointers are the special type of variables that are used to store the memory address of another variable. And, a structure (struct) is mainly used to create a customized type that can hold all other data types.

By using the pointer to a structure (struct), we can easily manipulate/access the data assigned to a struct. To use the pointer to a struct we use "&" (address operator/ address of operator). By using this we can access the fields of a struct without de-referencing them explicitly.

Consider the below examples demonstrating the instantiation struct pointer address operator in Golang.

Example 1:

// Golang program to instantiate
// struct pointer address operator

package main

import "fmt"

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

func main() {
	std := &student{"Alex", 108, 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:

// Golang program to instantiate
// struct pointer address operator

package main

import "fmt"

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

func main() {
	add1 := &Address{"Alex", "New Delhi", 110065}
	add2 := &Address{"Alvin", "Mumbai", 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 »

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


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.