声明接收器方法的数组

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

Declaring array of receiver methods

问题

这是一个使用函数数组的小例子。我想将其转换为接收器方法的数组。在第11行,数组的正确声明是什么?函数声明将从:

  1. func addToStock(s *Stock, add int)

变为:

  1. func (s *Stock) addToStock(add int)
英文:

Here's a small example using an array of functions. I want to convert this to an array of receiver methods. What would be the proper declaration for the array on line 11? https://play.golang.org/p/G62Cxm-OG2&lt;br /><br />
The function declarations would change from:<br />
func addToStock(s *Stock, add int)<br /><br />
To:<br />
func (s *Stock) addToStock(add int)

答案1

得分: 0

你可以这样做:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type Stock struct {
  6. qty int
  7. }
  8. var updaters = [2]func(*Stock, int){
  9. func(s *Stock, i int) { s.add(i) },
  10. func(s *Stock, i int) { s.remove(i) },
  11. }
  12. func main() {
  13. s := Stock{10}
  14. fmt.Println("库存数量 =", s.qty)
  15. updaters[0](&s, 2)
  16. fmt.Println("库存数量 =", s.qty)
  17. updaters[1](&s, 5)
  18. fmt.Println("库存数量 =", s.qty)
  19. }
  20. func (s *Stock) add(add int) {
  21. s.qty += add
  22. }
  23. func (s *Stock) remove(sub int) {
  24. s.qty -= sub
  25. }

这是一个简单的Go语言程序,它定义了一个名为Stock的结构体,表示库存。程序中定义了两个函数,分别用于增加和减少库存数量。通过调用updaters数组中的函数,可以对库存数量进行更新。在main函数中,首先创建了一个库存对象s,并打印出初始的库存数量。然后通过调用updaters数组中的第一个函数,将库存数量增加了2,并再次打印出更新后的库存数量。最后,通过调用updaters数组中的第二个函数,将库存数量减少了5,并再次打印出更新后的库存数量。

英文:

You can do like these:

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. )
  5. type Stock struct {
  6. qty int
  7. }
  8. var updaters = [2]func(*Stock, int){
  9. func(s *Stock, i int){s.add(i)},
  10. func(s *Stock, i int){s.remove(i)},
  11. }
  12. func main() {
  13. s := Stock{10}
  14. fmt.Println(&quot;Stock count =&quot;, s.qty)
  15. updaters[0](&amp;s, 2)
  16. fmt.Println(&quot;Stock count =&quot;, s.qty)
  17. updaters[1](&amp;s, 5)
  18. fmt.Println(&quot;Stock count =&quot;, s.qty)
  19. }
  20. func (s *Stock)add(add int) {
  21. s.qty += add
  22. }
  23. func (s *Stock)remove(sub int) {
  24. s.qty -= sub
  25. }

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

发表评论

匿名网友

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

确定