duaiwu8385 2017-06-15 01:25
浏览 33
已采纳

突变值

Can someone please tell me how to mutate the value of type Clock.

Basically when I call New() I get the output 3:04 and after calling ADD() function I expect the value to be 03:09. If I assign the value of ADD() function call then I get 03:09 as output. I was wondering is it possible to mutate the value of the type Clock using pointers?

package main

import "fmt"

const testVersion = 4

type Clock int

func New(hour, minute int) Clock {
    result := (hour*60 + minute) % (24*60)
    if result < 0 {
        result = result + 24*60
    }

    return Clock(result)
}

func (c Clock) String() string {
    return fmt.Sprintf("%02v:%02v", int(c/60), int(c%60))
}

func (c Clock) Add(minutes int) Clock{
    newC:=New(0,minutes + int(c))
    //fmt.Println(a)
}

func main() {
    result := New(3, 4)
    fmt.Println(result)
    result.Add(5)
    fmt.Println(result)
}
  • 写回答

1条回答 默认 最新

  • doulin4844 2017-06-15 03:31
    关注

    Yes, it is possible. If you are going to modify the value, you must define Add method on pointer receiver, e.g.

    func (c *Clock) Add(minutes int) Clock{
        *c =New(0,minutes + int(*c))
    
        return *c
    }
    

    Basic rule is: use pointer receiver if you're going to change the receiver value (except for slice and map which act as reference). Take a look at the following materials for better understanding on method receiver:

    1. The Go tour on Methods

    2. FAQ: Should I define methods on values or pointers?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。