Skip to main content

Posts

Showing posts with the label Go structs

Comparing Structs in Go

We can compare two structs in two ways:     1. Equal to (==) Operator     2. DeepEqual() Method in reflect package Example using (==) Operator : package main import "fmt" type User struct { name string age int } func main() { u1 := User{"tejas", 23} u2 := User{"tejas", 23} u3 := User{"vicky", 22} fmt.Println("Comparing u1 and u2 struct :", u1 == u2) fmt.Println("Comparing u1 and u3 struct :", u1 == u3) } Output: Comparing u1 and u2 struct : true Comparing u1 and u3 struct : false Example using DeepEqual() Method : package main import ( "fmt" "reflect" ) type User struct { name string age int } func main() { u1 := User{"tejas", 23} u2 := User{"tejas", 23} u3 := User{"vicky", 22} fmt.Println("Comparing u1 and u2 struct :", reflect.DeepEqual(u1, u2)) fmt.Println("Comparing u1 and u3 struct :", reflect.DeepEqual(u1, u3)) } Outpu...

Nested Struct in Go

A Struct which has a field of another struct is called Nested struct Example : package main import "fmt" type User struct { name string age int address Address } type Address struct { city string state string pincode int } func main() { // declare a struct variable & initialize it after var user1 User user1.name = "vicky" user1.age = 22 user1.address.city = "chennai" user1.address.state = "tamilnadu" user1.address.pincode = 600001 // declaration and initialization of nested struct user2 := User{"tejas", 23, Address{"madurai", "tamilnadu", 600001}} fmt.Println(user1) fmt.Println(user2) } Output: user 1 : {vicky 22 {chennai tamilnadu 600001}} user 2 : {tejas 23 {madurai tamilnadu 600001}} Important Note: we can embed an another struct into a struct by anonymously providing no name to the struct field package main import "fmt" type User struct { name string...

Structs in Golang

A struct in Golang is a user-defined type that allows to combine different types of variables into single type. In Golang, Structures does not support inheritance but supports composition. We can define a struct using a keyword struct. Syntax: type struct_name struct{} Example : package main import "fmt" type User struct { name string age int } func main() { // declare a struct variable var user1 User user1.name = "vicky" user1.age = 22 // declaration and initialization of struct at a same to a struct variable user2 := User{"tejas", 23} // you can define a struct address to a varibale while initializing user3 := &User{"vinu", 23} fmt.Println("user 1 : "user1) fmt.Println("user 2 : "user2) fmt.Println("user 3 : "*user3) } Output: user 1 : {vicky 22} user 2 : {tejas 23} user 3 : {vinu 23} Anonymous Struct in Golang: A anonymous struct is a struct with no name. It's useful when...