用自定义类型包装net.IP并在golang中添加方法

I try to add methodes to net.IP. Therefore I created a custom type IPAddr:

package main

import (
    "encoding/json"
    "net"
    "log"
)

func readNetworks(data []byte) (*[]Network, error) {
    var networks []Network

    if err := json.Unmarshal(data, &networks); err != nil {
        return &networks, err
    }

    return &networks, nil
}

type IPAddr net.IP

type Network struct {
    CIDR          string        `json:"cidr"`
    Gateway       IPAddr        `json:"gateway"`
}

func (ip *IPAddr) copy() IPAddr {
    if x := ip.To4(); x != nil {
        ip = x
    }
    dup := make(IPAddr, len(ip))
    copy(dup, ip)
    return dup
}

func main() {
    _, err := readNetworks([]byte("[{\"cidr\":\"10.100.19.0/24\",\"gateway\":\"10.100.19.1\"}]"))
    if err != nil {
        log.Fatal(err)
    }
}

Some things that do not work here:

  • Method To4() from net.IP is not known for IPAddr (line 27)
  • len() does not work for IPAddr but for net.IP (line 30)
  • string cannot be unmarshalled to IPAddr, this works for net.IP (line 12)

My type definition is obviously wrong... any hints?

See example at: http://play.golang.org/p/BT7VFnbPZW

Methods are not inherited between types (Go does not have inheritance at all).

You may want to embed the type, if promoting the methods automatically is what you're after:

type IPAddr struct {
    net.IP
}

Convert to net.IP before trying to call methods, otherwise you'll call methods on the wrapper:

func (ip *IPAddr) copy() IPAddr {
    if x := net.IP(*ip).To4(); x != nil {
        ip = x
    }
    dup := make(IPAddr, len(net.IP(*ip)))
    copy(dup, *ip)
    return dup
}

For unmarshaling, implement the json.Unmarshaler interface.

Another way to do it is by embedding net.IP in a struct, although this will inherit all methods from net.IP.