Skip to content

Any way to do value-predicated filtering (rather than type) #270

Open
@thockin

Description

@thockin

I have a function like this:

type T {
    // ... 
    IPs []string
    Port int
}

func Create(input T) T {
    output := T{}
    // ...

    // If user provided IPs, use that.  Else find free ones.
    if len(input.IPs) > 0 {
        output.IPs = input.IPs
    } else {
        output.IPs = allocateIPs()
    }

    // If user provided Port, use that.  Else find a free one.
    if input.Port != 0 {
        output.Port = input.Port
    } else {
        output.Port = allocatePort()
    }

    return output
}

I'm trying to use cmp.Equal and cmp.Diff to test. I specifically want to test permutations where the input specifies and doesn't specify input IPs and ports. The real logic is significantly more complicated than this reductive example, obviously.

What I am looking for is a cmp.Option similar to IgnoreFields (since the type is []string) crossed with Comparer(), but without the symmetric requirement. For example:

cmpIPs := FieldComparer(T{}, "IPs", func(x, y []string) bool {
    if len(x.IPs) == 0 {
        return true
    }
    return reflect.DeepEqual(x.IPs, y.IPs)
}
cmpPort := FieldComparer(T{}, "Port", func(x, y int) bool {
    if x.Port == 0 {
        return true
    }
    return x.Port == y.Port
}
cmp.Equal(input, output, cmpIPs, cmpPort)

Is this possible to express?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions