Câu hỏi phỏng vấn Golang
Câu hỏi

How to compare two...

Câu trả lời

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:

  1. Nil Interface Values: Two interface values are comparable and considered equal if both are nil.

  2. Non-Nil Interface Values: If both interface values are non-nil, they are comparable if:

    • They have the same underlying type.
    • The underlying type is comparable according to the Go specification (e.g., boolean, numeric, string, pointer, channel, interface types, structs with all comparable fields, arrays with comparable element types).
    • The underlying values are also equal.
  3. Use of Operators: You can use the == and != operators to compare two interfaces directly.

  4. 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:

go Copy
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

expert

Gợi ý câu hỏi phỏng vấn

junior

Can you declared multiple types of variables in single declaration in Go?

expert

When go runtime allocates memory from heap, and when from stack?

middle

How to check if a Map contains a key in Go?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào