声明接收器方法的数组
问题描述:
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
The function declarations would change from:
func addToStock(s *Stock, add int)
To:
func (s *Stock) addToStock(add int)
这是一个使用函数数组的小示例。 我想将其转换为接收器方法的数组。 第11行的数组正确的声明是什么? https://play.golang.org/p/G62Cxm-OG2
函数声明将更改为:
func addToStock(s *股票,添加int)
To:
func(s *股票)addToStock(添加int)
div>
答
You can do like these:
package main
import (
"fmt"
)
type Stock struct {
qty int
}
var updaters = [2]func(*Stock, int){
func(s *Stock, i int){s.add(i)},
func(s *Stock, i int){s.remove(i)},
}
func main() {
s := Stock{10}
fmt.Println("Stock count =", s.qty)
updaters[0](&s, 2)
fmt.Println("Stock count =", s.qty)
updaters[1](&s, 5)
fmt.Println("Stock count =", s.qty)
}
func (s *Stock)add(add int) {
s.qty += add
}
func (s *Stock)remove(sub int) {
s.qty -= sub
}