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条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度