I was using an excellent go icmp library recently. I got hung up on dealing with a received MessageBody type that I knew was really an Echo type, but I could not refer to the fields in the Echo
struct. I think my C/C++/Python background got in my way here.
After a bit of head scratching, I noticed the MessageBody
type was defined an an interface and the Echo
type was defined as a struct. Ah! A clue! I bet I can cast an interface type to a struct type.
Thusly:
switch rxMsg.Type {
case ipv4.ICMPTypeEchoReply:
body, _ := rxMsg.Body.(*icmp.Echo)
where rxMsg.Body
is the received icmp.MessageBody
interface and body
is the desired icmp.Echo
struct.
Insert blinding flash o' light here. Using an interface definition, this Go icmp library author allows the library user to easily convert an received message body into its appropriate struct equivalent. Whoa. That sort of power was not so obvious to me when I first read about the Go interface.
Pragmatic programmer. Consilient alchemist. Serial hobbyist. Pro geek. Miniature tabletop gamer.