How to compare two...
How to compare two...
To compare two interfaces in Go, you need to understand the internal representation of an interface and the rules that govern interface comparison. An interface in Go is represented internally by a tuple consisting of a type and a value. The type is the underlying type of the value that the interface holds, and the value is the actual data.
Here are the rules for comparing two interfaces in Go:
Nil Interface Values: Two interface values are comparable and considered equal if both are nil.
Non-Nil Interface Values: If both interface values are non-nil, they are comparable if:
Use of Operators: You can use the ==
and !=
operators to compare two interfaces directly.
Special Cases: Some types are not comparable in Go, such as slices, maps, and functions. If you attempt to compare interfaces holding values of these types, the comparison will result in a runtime panic.
Here is an example program that demonstrates interface comparison in Go:
package main
import "fmt"
type animal interface {
breathe()
walk()
}
type lion struct {
age int
}
func (l lion) breathe() {
fmt.Println("Lion breathes")
}
func (l lion) walk() {
fmt.Println("Lion walks")
}
func main() {
var a animal
var b animal
var c animal
var d animal
var e animal
a = lion{age: 10}
b = lion{age: 10}
c = lion{age: 5}
// Comparing non-nil interfaces with the same underlying type and value
if a == b {
fmt.Println("a and b are equal")
} else {
fmt.Println("a and b are not equal")
}
// Comparing non-nil interfaces with the same underlying type but different values
if a == c {
fmt.Println("a...
expert
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào