How to compare Structs with the Different Values Assigned to Data Fields in Golang?
Last Updated :
26 May, 2020
A struct (Structure) is a user-defined type in Golang that contains a collection of named fields/properties which creates own data types by combining one or more types. Also, this concept is generally compared with the classes in object-oriented programming. A struct has different fields of the same or different data types and is declared by composing a fixed set of unique fields.
Defining a struct type: The declaration of the struct starts with the keyword type, then a name for a new struct is defined and followed by keyword struct. After that curly bracket starts with defining a series of data fields with a name and a type.
Syntax:
type StructName struct {
field1 fieldType1
field2 fieldType2
}
Example:
type Employee struct {
firstName string
lastName string
salary int
age int
}
|
Below examples are given to explain- Using a comparison operator, structs of the same type can be compared.
Example 1:
package main
import "fmt"
type Employee struct {
FirstName, LastName string
Salary int
Age int
}
func main() {
A1 := Employee{
FirstName: "Seema" ,
LastName: "Singh" ,
Salary: 20000,
Age: 23,
}
A2 := Employee{
FirstName: "Seema" ,
LastName: "Singh" ,
Salary: 20000,
Age: 23,
}
if A1 == A2 {
fmt.Println( "Variable A1 is equal to variable A2" )
} else {
fmt.Println( "Variable A1 is not equal to variable A2" )
}
}
|
Output:
Variable A1 is equal to variable A2
Example 2:
package main
import "fmt"
type triangle struct {
side1 float64
side2 float64
side3 float64
color string
}
func main() {
var tri1 = triangle{10, 20, 30, "Green" }
tri2 := triangle{side1: 20, side2: 10,
side3: 10, color: "Red" }
if tri1 == tri2 {
fmt.Println( "True" )
} else {
fmt.Println( "False" )
}
tri3 := new (triangle)
var tri4 = &triangle{}
if tri3 == tri4 {
fmt.Println( "True" )
} else {
fmt.Println( "False" )
}
}
|
Output:
False
False
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...