改变数值

huangapple go评论77阅读模式
英文:

Mutate the value

问题

请问有人可以告诉我如何改变类型为Clock的值吗?

基本上,当我调用New()时,我得到的输出是3:04,在调用ADD()函数之后,我希望值变为03:09。如果我将ADD()函数调用的值赋给变量,那么输出就是03:09。我想知道是否可以使用指针来改变类型为Clock的值?

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)
}
英文:

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 &quot;fmt&quot;

const testVersion = 4

type Clock int

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

    return Clock(result)
}

func (c Clock) String() string {
    return fmt.Sprintf(&quot;%02v:%02v&quot;, 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

得分: 4

是的,这是可能的。如果你要修改值,你必须在指针接收器上定义Add方法,例如:

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

基本规则是:如果你要改变接收器的值(除了slicemap作为引用之外),请使用指针接收器。请参考以下材料以更好地理解方法接收器:

  1. Go 之旅:方法
  2. 常见问题解答:我应该在值上还是指针上定义方法?
英文:

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?

huangapple
  • 本文由 发表于 2017年6月15日 09:25:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/44557109.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定