douzi8916 2015-04-20 15:05
浏览 84
已采纳

用自定义类型包装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

  • 写回答

2条回答 默认 最新

  • dqv84329 2015-04-20 15:08
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改