Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I compare net.Addr?

Tags:

go

I am trying to understand/learn why I can't compare two identical net.Addr.

From this post, it seems that two interfaces should be able to be compared if they are of the same underlying type and that type can be compared. In my example below, the underlying type is net.UDPAddr. It is a struct containing a string, int and a net.IP, which is a type alias of []byte.

Is it because the slice IP is not comparable? Even though its type, length and contents are identical?

Example:

https://go.dev/play/p/dIzRCTwBA4P

like image 859
Ashley Duncan Avatar asked Mar 07 '26 19:03

Ashley Duncan


1 Answers

Your example compares the values returned from two calls to net.ResolveUDPAddr. However if you consider the function signature:

func ResolveUDPAddr(network, address string) (*UDPAddr, error)

You will note that you are actually comparing two pointers; these are comparable but will not be equal (you are comparing the pointer; not the value it points to).

As per the go spec:

Struct types are comparable if all their field types are comparable.
Slice, map, and function types are not comparable. However, as a special case, a slice, map, or function value may be compared to the predeclared identifier nil.

net.UDPAddr contains a net.IP which is a []byte and, therefore, not comparable.

This extension of your example may help.

like image 159
Brits Avatar answered Mar 09 '26 16:03

Brits



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!