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

How can I check if t...

Câu trả lời

To check if two slices are equal in Go, you have several methods available depending on the version of Go you are using and the specific requirements of your comparison. Here are the primary methods:

Using the Standard Library (Go 1.21 and later)

For Go version 1.21 and later, you can use the Equal function from the slices package in the standard library. This function compares two slices for equality, where equality means both slices have the same length and corresponding elements are equal.

package main

import (
    "fmt"
    "slices"
)

func main() {
    a := []int{1, 2, 3}
    b := []int{1, 2, 3}
    fmt.Println("Slices equal:", slices.Equal(a, b))
}

Using reflect.DeepEqual

For a more general solution that works with slices of any type, you can use reflect.DeepEqual. This function from the reflect package checks if two slices are deeply equal, meaning all corresponding elements and their sub-elements are equal.

package main

import (
    "fmt"
    "reflect"
)

func main() {
    a := []int{1, 2, 3}
    b := []int{1, 2, 3}
    fmt.Println("Slices equal:", reflect.DeepEqual(a, b))
}

Writing a Custom Function

If you need a custom comparison logic or are using an older version of Go that does not support the slices package, you can write your own function to compare two slices. This method involves iterating over the slices and comparing each element.

package main

import "fmt"

func slicesEqual(a, b []int) bool...
senior

senior

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

senior

When is the init() function run?

junior

Why the Go language was created?

middle

Why would you prefer to use an empty struct{} ?

Bình luận

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

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