突变值

突变值

问题描述:

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

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?