You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
package main
import (
"fmt""net"
)
funcmain() {
udpServerAddr, err:=net.ResolveUDPAddr("udp", "127.0.0.1:0")
iferr!=nil {
panic(err)
}
udpServer, err:=net.ListenUDP("udp", udpServerAddr)
fmt.Printf("udpServer is a %T\n", udpServer)
localAddr:=udpServer.LocalAddr()
fmt.Printf("localAddr is a %T, value %#v, string %s\n", localAddr, localAddr, localAddr)
//fmt.Printf("localPort is %d\n", localAddr.Port)
}
fmt sees localAddr as a net.UDPAddr:
udpServer is a *net.UDPConn
localAddr is a *net.UDPAddr, value &net.UDPAddr{IP:net.IP{0x7f, 0x0, 0x0, 0x1}, Port:46866, Zone:""}, string 127.0.0.1:46866
Uncommenting line 19 breaks the program because localAddr is not what fmt says:
./prog.go:19:44: localAddr.Port undefined (type net.Addr has no field or method Port)
The text was updated successfully, but these errors were encountered:
net.Addr is an interface that could have many concrete implementations, including net.UDPAddr. There are no requirements on the String() formatting.
If you want the port, type assert it.
The following sample program is currently also available at https://go.dev/play/p/KX6uPkxjFy_w
fmt sees localAddr as a net.UDPAddr:
Uncommenting line 19 breaks the program because localAddr is not what fmt says:
The text was updated successfully, but these errors were encountered: