英文:
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 "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
得分: 4
是的,这是可能的。如果你要修改值,你必须在指针接收器上定义Add
方法,例如:
func (c *Clock) Add(minutes int) Clock{
*c = New(0, minutes + int(*c))
return *c
}
基本规则是:如果你要改变接收器的值(除了slice
和map
作为引用之外),请使用指针接收器。请参考以下材料以更好地理解方法接收器:
- Go 之旅:方法
- 常见问题解答:我应该在值上还是指针上定义方法?
英文:
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:
-
The Go tour on Methods
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论