dongyi3616 2018-06-06 23:31
浏览 263
已采纳

在Golang中返回一个新的Struct实例

My goal is to return a new DDIAddress from EndRangeTest(); however, when I try to do this, subsequent calls to EndRangeTest seem to modify the same struct instance instead of creating a new object.

For instance, when I run the code below, I expect tRange to be 127.0.0.255 and sRange equal to 255.0.0.20. But what actually happens is that s.EndRangeTest() modifies tRange.

t := new(DDIAddress)
s := new(DDIAddress)

t.FromString("127.0.0.1")
t.cidr = 24

s.FromString("255.0.0.20")
s.cidr = 32

tRange := t.EndRangeTest()
fmt.Printf("T Result:%s
", tRange.String())

sRange := s.EndRangeTest()

fmt.Printf("S Result:%s
", sRange.String())
fmt.Printf("T Result:%s


", tRange.String())

Output:

T Result:127.0.0.255
S Result:255.0.0.20
T Result:255.0.0.20

I am new to Go, and don't understand what I am doing wrong here.

My DDIAddress struct is implemented as followed:

type DDIAddress struct {
    net.IP
    cidr uint32
}

func (addr *DDIAddress) EndRangeTest() (DDIAddress) {
   var maskSize int
   var start int

   endAddr := DDIAddress{}

   if addr.isIPv4() == false {
      maskSize = 16
      start = 0
      endAddr.IP = net.IPv6zero
   }else{
      maskSize = 4
      start = 12
      endAddr.IP = net.IPv4zero
   }

   mask := net.CIDRMask(int(addr.cidr), 8*maskSize)

   for i :=0; i < maskSize; i++{
      endAddr.IP[start] = addr.IP[start] | (mask[i] ^ 0xff)
      start++
   }

   return endAddr
}

Thanks!

  • 写回答

1条回答 默认 最新

  • doufei8250 2018-06-06 23:41
    关注

    The values created by EndRangeTest share the backing arrays of net.IPv6zero or net.IPv4zero. A change to the backing array of one DDIAddress changes the backing array of other DDIAddress values of the same size.

    To fix the problem, allocate a new slice:

       if addr.isIPv4() == false {
          maskSize = 16
          start = 0
          endAddr.IP = make(net.IP, net.IPv6len)
       } else {
          maskSize = 4
          start = 12
          endAddr.IP = make(net.IP, net.IPv4len)
       }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?