dongwo1234 2016-12-26 19:00
浏览 12
已采纳

使用指针接收器更改非结构的值

If I have a type which is not a struct how do I change its value with a pointer receiver?

For example, given the following code:

package main

import (
    "fmt"
)

type MyInt int

func (i *MyInt) Change() {
    newValue := MyInt(32)
    i = &newValue
}

func main() {
    myInt := MyInt(64)
    fmt.Println(myInt)
    myInt.Change()
    fmt.Println(myInt)
}

It outputs:

64
64

Why does it not output the following:

64
32

?

  • 写回答

2条回答 默认 最新

  • dougu3591 2016-12-26 19:03
    关注

    You're changing the value of the pointer i, not the value at which the pointer is pointing.

    You will see your expected output by using the * operator:

    *i = newValue
    

    https://play.golang.org/p/mKsKC0lsj9

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?