How to Test Equivalence of Maps in Golang?

Mary-Kate Olsen
Release: 2024-11-16 22:26:03
Original
490 people have browsed it

How to Test Equivalence of Maps in Golang?

Testing Equivalence of Maps in Golang

When writing table-driven tests that involve maps, determining their equivalence can be challenging. One approach is to manually check for equality of lengths and individual key-value pairs, but this becomes repetitive for different map types.

Idiomatic Approach

The Go library offers a built-in solution: reflect.DeepEqual. This function takes two interface{} arguments and recursively compares their values. For maps, it compares lengths, keys, and values using the following steps:

  1. Checks if both maps are nil.
  2. Ensures they have the same length.
  3. Verifies if they have the same set of (key, value) pairs.

Example Usage

To compare two maps, m1 and m2, use the following code:

import "reflect"

eq := reflect.DeepEqual(m1, m2)
if eq {
    fmt.Println("They're equal.")
} else {
    fmt.Println("They're unequal.")
}
Copy after login

This solution avoids the need for custom comparison logic and works with various map types. However, note that it will also compare non-map values if passed incorrectly.

The above is the detailed content of How to Test Equivalence of Maps in Golang?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template