Structs

Structs are type collection of fields. We can use struct to group data together and can form records.

struct declaration and creating instance variable

package main

import (
	"fmt"
	)

type Student struct {
	Name string
	Age int
}

func main() {
	// Create instance of student
	var john Student
	
	// Assign values
	john.Name = "John Cena"
	john.Age = 45

	// Print struct
	fmt.Println("Name: ", john.Name) // Name:  John Cena
	fmt.Println("Age: ", john.Age) // Age:  45

	// Create another instance
	bhaw := Student{"Bhawani", 30}
	// Print struct
	fmt.Println("Name: ", bhaw.Name) // Name:  Bhawani
	fmt.Println("Age: ", bhaw.Age) // Age:  30

	// Create one more instanct
	asha := Student{Name: "Asha", Age: 30}
	fmt.Println("Name: ", asha.Name) // Name:  Asha
	fmt.Println("Age: ", asha.Age) // Age:  30
}

struct with pointer

package main

import "fmt" 

type Number struct {
	Value int
}

func main() {
	// Create instance of Number 
	var num Number

	// Use of pointer on a struct field
	var ptrNum *int
	ptrNum = &num.Value
	*ptrNum = 10

	// Print struct field value
	fmt.Println("num.Value =", num.Value)

	// Use of pointer
	num1 := Number{Value: 30}
	ptrNum1 := &num1
	ptrNum1.Value = 40
	
	// Print struct field value
	fmt.Println("num1.Value =", num1.Value)
	fmt.Println("num1.Value =", ptrNum1.Value)
}

struct with pointer

package main

import "fmt" 

type Number struct {
	Value int
}

func main() {
	// Create instance of Number 
	var num Number

	// Use of pointer on a struct field
	var ptrNum *int
	ptrNum = &num.Value
	*ptrNum = 10

	// Print struct field value
	fmt.Println("num.Value =", num.Value)

	// Use of pointer
	num1 := Number{Value: 30}
	ptrNum1 := &num1
	ptrNum1.Value = 40
	
	// Print struct field value
	fmt.Println("num1.Value =", num1.Value)
	fmt.Println("ptrNum1.Value =", ptrNum1.Value)
}

comparing two structs

package main

import "fmt"

type Number struct {
X int
Y int
}

func main() {
num1 := Number{10, 20}
num2 := Number{20, 10}

fmt.Println(num1 == num2) // false
fmt.Println(num1.X == num2.X && num1.Y == num2.Y) // false

n1 := Number{10, 20}
n2 := Number{10, 20}

fmt.Println(n1 == n2) // true
fmt.Println(n1.X == n2.X && n1.Y == n2.Y) // true
}

Leave a Reply

Your email address will not be published. Required fields are marked *